python定义字符串数组,python ctypes中的多维char数组(字符串数组)

I'm trying to pass an array of character arrays to a C function using ctypes.

void cfunction(char ** strings)

{

strings[1] = "bad"; //works not what I need.

strings[1][2] = 'd'; //this will segfault.

return;

}

char *input[] = {"foo","bar"};

cfunction(input);

Since the array that I throw around is statically defined anyways,

I just changed the function declaration and input parameter like so:

void cfunction(char strings[2][4])

{

//strings[1] = "bad"; //not what I need.

strings[1][2] = 'd'; //what I need and now it works.

return;

}

char input[2][4] = {"foo","bar"};

cfunction(input);

Now I run into the problem of how to define this multi-dimensional character

array in python. I had thought it would go like so:

import os

from ctypes import *

libhello = cdll.LoadLibrary(os.getcwd() + '/libhello.so')

input = (c_char_p * 2)()

input[0] = create_string_buffer("foo")

input[1] = create_string_buffer("bar")

libhello.cfunction(input)

This gives me TypeError: incompatible types, c_char_Array_4 instance instead of c_char_p instance. If I change it to:

for i in input:

i = create_string_buffer("foo")

Then I get segmentation faults. Also this looks like the wrong way to build the 2d array because if I print input I see None:

print input[0]

print input[1]

# outputs None, None instead of "foo" and "foo"

I also run into the issue of using #DEFINE MY_ARRAY_X 2 and #DEFINE MY_ARRAY_Y 4 to keep the array dimensions straight in my C files, but don't know a good way to get these constants out of the libhello.so so that python can reference them when it constructs the datatypes.

解决方案

Use something like

input = ((c_char * 4) * 2)()

input[0].value = "str"

input[0][0] == "s"

input[0][1] == "t" # and so on...

Simple usage:

>>> a =((c_char * 4) * 2)()

>>> a

>>> a[0]

>>> a[0].raw

'\x00\x00\x00\x00'

>>> a[0].value

''

>>> a[0].value = "str"

>>> a[0]

>>> a[0].value

'str'

>>> a[0].raw

'str\x00'

>>> a[1].value

''

>>> a[0][0]

's'

>>> a[0][0] = 'x'

>>> a[0].value

'xtr'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值