如何将 Python 字符串传递给 C++ (extern C) 函数



我有q.cpp

#include <string>
#include <iostream>
extern "C" {
int isNExist (std::string* sequence) {
std::cout << sequence << std::endl;
// here I want to process input string and return some int value
return 0;
}
}

q.py

from ctypes import cdll, c_char_p, c_int
lib = cdll.LoadLibrary('mylib.so')
lib.isNExist.restype = c_int
lib.isNExist.argtypes = [c_char_p]
string = "Hello world!".encode("UTF-8")
lib.isNExist(string)

打开厘米:

g++ -c -fPIC q.cpp -o q.o
g++ -shared -Wl,-soname,mylib.so -o mylib.so  q.o

当我运行(32位(python q.py时,它返回一个错误:

Traceback (most recent call last):
File "q.py", line 27, in <module>
print(lib.isNExist(string))
OSError: exception: access violation reading 0x43544741

我应该如何将值正确传递给C++(在这种情况下为 C,因为我使用 extern C(函数来使用它?

编辑:

我稍微编辑了一下代码并尝试使用 char 而不是字符串:

问.cpp:

#include <string>
#include <iostream>
extern "C" {
int isNExist (char* sequence) {
std::cout << sequence << std::endl;
return 0;
}
}

q.py

from ctypes import cdll, c_char_p, c_char, c_float, c_int,c_wchar_p, POINTER
lib = cdll.LoadLibrary('mylib.so')

# send strings to c function
lib.isNExist.argtypes = [POINTER(c_char_p)]
lib.isNExist.restype = c_int
s = "Hello world!".encode("UTF-8")
string_length = len(s)
string_type = c_char_p*string_length
#print(string_type)
result = lib.isNExist(string_type(*s))

它只传递并打印第一个字符("H"(,但我想传递完整的字符串。我该怎么办?

编辑2:

在 cpp 中,如果我在 isNEsixt 函数中传递字符串,它将正确打印整个字符串并且string_type<class '__main__.c_char_p_Array_12'>,所以我假设我在 Python 代码的结果行中缺少一些东西

>q.cpp文件应该保持原样。注释是用python代码编写的

#include <string>
#include <iostream>
extern "C" {
int isNExist (char* sequence) {
std::cout << sequence << std::endl;
return 0;
}

q.py

from ctypes import cdll, c_char_p, c_char, c_float, c_int,c_wchar_p,addressof, create_string_buffer,POINTER
# connect to .so
lib = cdll.LoadLibrary('mylib.so')
# set data types of arguments of cpp function
lib.isNExist.argtypes = [c_char_p]
# set result data type
lib.isNExist.restype = c_int
# string I want to pass to the function
s = "Hello world!".encode("UTF-8")
# create buffer that will pass my string to cpp function
buff = create_string_buffer(s)
# passing buff to function
result = lib.isNExist(buff)

最新更新