[英]How to pass string parameters to C++ function using ctypes, python
[英]How to pass Python string to C++ (extern C) function
我有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)
打開 cmd:
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)function 來使用它?
編輯:
我稍微編輯了我的代碼並嘗試使用 char 而不是字符串:
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 中,如果我在 isNEixt function 中傳遞字符串,它將正確打印整個字符串並且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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.