[英]How to pass const char* from python to c function
I am using ctypes
in Python to open a file for writing in C++. 我在Python中使用ctypes
来打开一个用C ++编写的文件。
My C++ code: 我的C ++代码:
extern "C" {
void openfile(const char *filename) {
cout<<"File to open for writing = " <<filename<<endl;
FILE *fp = fopen(filename,"w");
fprintf(fp,"writing into file");
fclose(fp);
}
}
My Python code: 我的Python代码:
>>> 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. 我得到的文件名为m
,这是我文件的第一个char
。
How to pass whole string to the C side? 如何将整个字符串传递给C端?
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. 在python3中(你肯定在python2上使用python3,你的代码很幸运)字符串存储为wchar_t[]
缓冲区,所以当你传递"myfirstfile.txt"
,C函数将其arg视为"m\\0y\\0..."
这显然是一个长度为C的字符串。 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 你应该向C函数传递一个bytes
对象
In [23]: puts(b'abc')
abc
You can convert str
to bytes
like this: 您可以将str
转换为bytes
如下所示:
puts(my_var.encode())
To avoid further confusion you may specify the argument types of C function: 为避免进一步混淆,您可以指定C函数的参数类型:
In [27]: puts.argtypes = [c_char_p]
Now the function accepts bytes
(ctypes converts it to char*
): 现在该函数接受bytes
(ctypes将其转换为char*
):
In [28]: puts(b'abc')
abc
but not str
: 但不是str
:
In [30]: puts('abc')
---------------------------------------------------------------------------
ArgumentError Traceback (most recent call last)
<ipython-input-26-aaa5b59630e2> in <module>()
----> 1 puts('abc')
ArgumentError: argument 1: <class 'TypeError'>: wrong type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.