2016-06-22 11 views
3

私は​​をPythonで使用して、C++での書き込み用ファイルを開きます。pythonからc関数にconst char *を渡す方法

私の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 

が、私は私のファイルの最初のchar charaterでm、などのファイル名を取得しています。

文字列全体をC側に渡す方法は? python3で

+0

あなたは、C++へのpython文字列からの変換のようなものを渡す必要があり ' ctypes.c_char_p( "myfirstfile.txt") ' – cdarke

+0

それでも、文字列全体をc側に渡すことができませんでした。 –

答えて

6

文字列wchar_t[]バッファとして保存されている(とあなたは間違いなくあなたのコードが運良く仕事が考えpython2上としてのpython3を使用している)ので、あなたは"myfirstfile.txt" を渡す際にC関数は、明らかにCの文字列である"m\0y\0..."としてその引数を見て長さ1の

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 

あなたがC関数にあなたは、このようstrbytesに変換することができbytesオブジェクト

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

渡す必要があります:さらに避けるために

puts(my_var.encode()) 

をここ は、問題が顕在化しますあなたはC関数の引数型を指定することができます:

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

なくstr

In [27]: puts.argtypes = [c_char_p] 
今関数は( char*に変換ctypesの) bytesを受け入れ

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 
+0

ありがとうございます。私はバイト( "myfirstfile.txt"、encoding = "ascii")を使って同様のことを行い、それがうまくいった。 –

関連する問題