我是靠谱客的博主 怕孤单乌冬面,最近开发中收集的这篇文章主要介绍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 "my..." 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

最后

以上就是怕孤单乌冬面为你收集整理的python const char,如何将const char *从python传递到C函数的全部内容,希望文章能够帮你解决python const char,如何将const char *从python传递到C函数所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(33)

评论列表共有 0 条评论

立即
投稿
返回
顶部