python const char_如何将const char *从python传递到C函数

I am using ctypes in Python to open a file for writing in C++.

My C++ code:

extern "C" {

void openfile(const char *filename) {

cout<

FILE *fp = fopen(filename,"w");

fprintf(fp,"writing into file");

fclose(fp);

}

}

My Python code:

>>> import ctypes

>>> lib = ctypes.cdll.LoadLibrary('/in/vrtime/mahesh/blue/rnd/software/test/test.so')

>>> outfile = "myfirstfile.txt"

>>> lib.openfile(outfile)

File to open for writing = m

I am getting the file name as m, which is the first char charater of my file.

How to pass whole string to the C side?

解决方案

In python3 (and you are definitely using python3 as on python2 your code would luckily work)

strings are stored as wchar_t[] buffers, so when you pass "myfirstfile.txt"

the C function sees its arg as "m\0y\0..." which is obviously a C string of lenght one.

Here is the problem manifested:

In [19]: from ctypes import cdll, c_char_p

In [20]: libc = cdll.LoadLibrary("libc.so.6")

In [21]: puts = libc.puts

In [22]: puts('abc')

a

You should pass to the C function a bytes object

In [23]: puts(b'abc')

abc

You can convert str to bytes like this:

puts(my_var.encode())

To avoid further confusion you may specify the argument types of C function:

In [27]: puts.argtypes = [c_char_p]

Now the function accepts bytes (ctypes converts it to char*):

In [28]: puts(b'abc')

abc

but not str:

In [30]: puts('abc')

---------------------------------------------------------------------------

ArgumentError Traceback (most recent call last)

in ()

----> 1 puts('abc')

ArgumentError: argument 1: : wrong type

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值