繁体   English   中英

如何将 Python 字符串传递给 C++(外部 C)function

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM