简体   繁体   English

需要ctypes char *指针

[英]ctypes char* pointer needed

I have a C function returning strings (char *), let's call it foo() . 我有一个C函数返回字符串(char *),让我们称之为foo() In python I want to call it and use it's return value, and when I'm done, I want to call an other C function which frees the string foo returned. 在python中我想调用它并使用它的返回值,当我完成后,我想调用另一个C函数来释放返回的字符串foo

How can I get both the pointer and the string itself? 如何获得指针和字符串本身? If I do like this: 如果我喜欢这样:

fooFunc = foolib.foo
fooFunc.restype = c_char_p
r = fooFunc()

Then I get the string, but not the pointer. 然后我得到字符串,但不是指针。 If I do it without specifying the restype , I get an int which seems to be the correct address, but whenever I try to cast it to sting with c_char_p(<address>) it crashes with segmentation fault. 如果我在没有指定restype情况下执行它,我得到一个似乎是正确地址的int,但每当我尝试使用c_char_p(<address>)c_char_p(<address>)为sting时,它就会因为分段错误而崩溃。

I'm surprised you can't just pass back the c_char_p instance to the second function, but I don't have the tools at hand to verify why it would fail. 我很惊讶你不能只将c_char_p实例传回第二个函数,但是我没有手头的工具来验证它为什么会失败。

However, as an alternative, I believe you could try: 但是,作为替代方案,我相信您可以尝试:

  • Specifying the restype as a simple pointer ( c_void_p ) restype指定为简单指针( c_void_p
  • When you want to manipulate the string, use ctypes.string_at to build it 如果要操作字符串,请使用ctypes.string_at来构建它
  • Pass the initially returned pointer to the freeing function. 将最初返回的指针传递给释放函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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