Python ctype:当 c 函数向其写入值时,c 函数的 char 数组未更新

Python ctype: char array to c function is not getting updated when the c function writes values to it

这是我的 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 将变量作为参数传递,但更新后的数组没有反映出来。非常感谢任何工作代码示例。

编辑:我正在使用 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);

A bytearray 不是将 char * 传递给 C 函数的正确方法。请改用 create_string_buffer。此外,len(data) 是一个差一错误,会导致空终止符不存在,因此要么在其上粘贴 + 1 或将其删除,因为默认长度是正确的。这是一个最小的工作示例。首先,一个将每个字母转为大写的 C 函数,以及 returns 已经大写的字母数:

#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'