2

C側に文字配列を含む構造があります

stuct s
{
    int x;
    char buffer[100];
}

そして私のpython側で私は定義します

class myS(ctypes.Structure):
    _fields_ = [("x", c_int),
         ("buffer",type(create_string_buffer(100)))]

今、私がするとき

buf = create_string_buffer(64)
s1 = myS(10,buf)

それは私にエラーを与える

TypeError: expected string or Unicode object, c_char_Array_100 found

C 関数によって変更される文字列が必要です。どうやってするの?

4

2 に答える 2

1

通常の Python 文字列を 100*c_char フィールドに割り当てることができます。

class myS(ctypes.Structure):
    _fields_ = [("x", c_int),
         ("buffer", 100*c_char)]

s1 = myS(10, "foo")
s1.buffer = "bar"

ただし、文字列バッファ オブジェクトがある場合は、その値を取得できます。

buf = create_string_buffer(64) 
s1 = myS(10,buf.value)

また、

>>> type(create_string_buffer(100)) == 100*c_char
True
于 2012-04-04T08:23:30.477 に答える
1

バッファを作成する必要はありません。インスタンス化すると、バッファは構造内にあります。

簡単な DLL を次に示します。

#include <string.h>

struct s
{
    int x;
    char buffer[100];
};

__declspec(dllexport) void func(struct s* a)
{
    a->x = 5;
    strcpy(a->buffer,"here is the contents of the string.");
}

これを呼び出す Python コードは次のとおりです。

import ctypes

class myS(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_int),
        ("buffer",ctypes.c_char * 100)]

s1 = myS()
dll = ctypes.CDLL('test')
dll.func(ctypes.byref(s1))
print s1.buffer
print s1.x

出力:

here is the contents of the string.
5
于 2012-04-04T08:25:24.863 に答える