如何通过ctype将字符串缓冲区从python函数传递到C Api
我有一个带有以下原型的C api函数,我希望通过ctypes模块从Python2.6/2.7调用该函数 C功能:如何通过ctype将字符串缓冲区从python函数传递到C Api,python,c,ctypes,Python,C,Ctypes,我有一个带有以下原型的C api函数,我希望通过ctypes模块从Python2.6/2.7调用该函数 C功能: int function_name( char *outputbuffer, int outputBufferSize, const char *input, const char *somestring2 ); 这里,outputbuffer是一种字符串缓冲区,在基于input和somestring2调用此函数后,将插入一个字符串作为输出
int function_name( char *outputbuffer, int outputBufferSize,
const char *input, const char *somestring2 );
这里,outputbuffer是一种字符串缓冲区,在基于input和somestring2调用此函数后,将插入一个字符串作为输出
如何在python中创建此缓冲区(输出缓冲区)以及此函数的argtype是什么首先,导入ctypes模块。然后您需要加载包含上述函数的c dll。之后,您需要设置该函数的参数类型和结果类型。最后,创建目标缓冲区并调用函数 Python:
import ctypes as ct
MAX_BUFSIZE = 100
mycdll = ct.CDLL("path_to_your_c_dll") # for windows you use ct.WinDLL(path)
mycdll.function_name.argtypes = [ct.c_char_p, ct.c_int,
ct.c_char_p, ct.c_char_p]
mycdll.function_name.restype = ct.c_int
mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
result = mycdll.function_name(mystrbuf, len(mystrbuf),
b"my_input", b"my_second_input")
使用strncpy的工作示例:
import ctypes as ct
MAX_BUFSIZE = 100
mycdll = ct.CDLL("libc.so.6") # on windows you use cdll.msvcrt, instead
mycdll.strncpy.argtypes = [ct.c_char_p, ct.c_char_p, ct.c_size_t]
mycdll.strncpy.restype = ct.c_char_p
mystrbuf = ct.create_string_buffer(MAX_BUFSIZE)
dest = mycdll.strncpy(mystrbuf, b"my_input", len(mystrbuf))
print(mystrbuf.value)
Python 3输出:
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 --version
Python 3.8.5
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python3 python_ctypes.py
b'my_input'
Python 2输出:
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 --version
Python 2.7.18
user@Mint20:~/Dokumente/Programmieren/sites/Stackoverflow$ python2 python_ctypes.py
my_input
我不是Python的专家,但是检查<代码> cType < /C>和<代码> CuraTyStRIGIGHULL < /COD>。为什么添加C++标签?这个问题清楚地表明,我们感兴趣的主题是“C api函数”。@pqans对于由此带来的任何不便表示歉意。我猜C++标签在推荐中,所以不小心添加了。将删除它。谢谢你的回答。我没有在mystrbuf中存储/返回输出。此外,我还尝试以您建议的两种方式发送输入,即b“my_input”和ct.c_char_p(“my_input”)。但mystrbuf仍然是空的。有什么想法吗?如果您分别在linux或windows上工作,请加载
libc.so.6
或msvcrt
,而不是加载您的c代码。将函数_名称替换为strncpy,并提供正确的arg和restype。然后你会发现它是有效的!您的c代码看起来怎么样?我刚刚添加了一个使用建议strncp的工作示例。还有一件事忘了添加,我正在使用python 2。Python2和Python3的ctypes有什么重大变化吗?请看,但是我不知道这个早期版本的特性集。