【问题标题】:How to pass const char* from python to c function如何将 const char* 从 python 传递给 c 函数
【发布时间】:2016-06-22 11:15:31
【问题描述】:

我在 Python 中使用ctypes 打开一个文件以便用 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端?

【问题讨论】:

  • 你需要从 python 字符串转换为 C++,传递类似ctypes.c_char_p("myfirstfile.txt")
  • 我检查过了,但仍然无法将整个字符串传递到 c 端。

标签: python ctypes python-c-api


【解决方案1】:

在 python3 中(你肯定会像在 python2 上一样使用 python3,你的代码很幸运可以工作) 字符串存储为wchar_t[] 缓冲区,因此当您传递"myfirstfile.txt" C 函数将其 arg 视为"m\0y\0...",这显然是一个长度为一的 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

【讨论】:

  • 谢谢。我通过使用 bytes("myfirstfile.txt", encoding="ascii") 做了类似的事情,它奏效了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2013-12-19
  • 2013-09-29
  • 2012-07-26
  • 2011-05-22
  • 1970-01-01
相关资源
最近更新 更多