这是我的 C 代码:
//int MyFunc(char* res); -> This is the definition of C function
char data[4096];
MyFunc(data);
printf("Data is : %s\n", data);
data
变量由 C 函数更新。我在 Python 中使用 bytearray
将变量作为参数传递,但更新后的数组没有反射(reflect)出来。非常感谢任何工作代码示例。
编辑:我正在使用 Python 3.7。 我的 Python 代码:
data = bytearray(b'1234567890')
str_buffer = create_string_buffer(bytes(data), len(data))
print(MyFunc(str_buffer))
print(str_buffer.value) #Output: b''
str_buffer
不包含由 MyFunc()
更新的值。
使用以下签名从 C# 调用 MyFunc()
对我有用。我正在寻找与之等效的 Python 3.7。
[DllImport("mydll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int MyFunc(StringBuilder data);
最佳答案
bytearray
不是将 char *
传递给 C 函数的正确方法。请改用 create_string_buffer
。此外,len(data)
是一个差一错误,会导致空终止符不存在,因此要么在其上粘贴一个 + 1
,要么将其删除,因为默认长度是正确的。这是一个最小的工作示例。首先,一个 C 函数将每个字母转为大写,并返回已经大写的字母数:
#include <ctype.h>
int MyFunc(char* res) {
int i = 0;
while(*res) {
if(isupper(*res)) {
++i;
} else {
*res = toupper(*res);
}
++res;
}
return i;
}
我用 gcc -fPIC -shared upstring.c -o upstring.so
编译了它。由于您使用的是 Windows,因此您必须对此进行调整。
现在,一些调用它的 Python:
from ctypes import *
upstring = CDLL("./upstring.so") # Since you're on Windows, you'll have to adapt this too.
data = bytearray(b'abc12DEFGHI')
str_buffer = create_string_buffer(bytes(data)) # Note: using len(data) would be an off-by-one error that would lose the null terminator, so either omit it or use len(data)+1
print(upstring.MyFunc(str_buffer)) # prints 6
print(str_buffer.value) # prints b'ABC12DEFGHI'
关于Python ctype : char array to c function is not getting updated when the c function writes values to it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61506316/