我有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,在这个例子中,我使用EXCENC C)函数来使用它?
编辑:
我稍微编辑了我的代码,并尝试使用char而不是string:
q.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代码编写的q.py
相关问题 更多 >
编程相关推荐