我ctypes
在Python中使用打开文件进行C ++编写。
我的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);
}
}
我的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
我得到的文件名为m
,这是char
文件的第一个字符。
如何将整个字符串传递给C端?
在python3中(并且您肯定会像在python2上一样使用python3,您的代码会很幸运地工作),字符串存储为wchar_t[]
缓冲区,因此当您传递"myfirstfile.txt"
C函数时,它会看到它的arg,"m\0y\0..."
这显然是一个长度为C的C字符串。这是表现出来的问题:
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
您应该将一个bytes
对象传递给C函数
In [23]: puts(b'abc')
abc
您可以转换str
成bytes
这样:
puts(my_var.encode())
为了避免进一步的混乱,您可以指定C函数的参数类型:
In [27]: puts.argtypes = [c_char_p]
现在该函数接受bytes
(ctypes将其转换为char*
):
In [28]: puts(b'abc')
abc
但不是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句