如何将Python字符串传递给C++;(外部C)功能
我有q.cpp如何将Python字符串传递给C++;(外部C)功能,python,c++,ctypes,Python,C++,Ctypes,我有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; }
#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;
}
}
打开命令:
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
它只传递并打印第一个字符('H'),但我想传递整个字符串。我该怎么办
编辑2:
在cpp中,如果我在isNEsixt函数中传递字符串,它将正确地打印整个字符串,并且
string\u type
是
,因此我假设我在Python代码的结果行中遗漏了一些内容。注释是用python代码编写的
#include <string>
#include <iostream>
extern "C" {
int isNExist (char* sequence) {
std::cout << sequence << std::endl;
return 0;
}
q.cpp
文件应该保持我的示例中的状态。注释是用python代码编写的
#include <string>
#include <iostream>
extern "C" {
int isNExist (char* sequence) {
std::cout << sequence << std::endl;
return 0;
}
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))
#include <string>
#include <iostream>
extern "C" {
int isNExist (char* sequence) {
std::cout << sequence << std::endl;
return 0;
}
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)