Python ctypes | TypeError

问题描述 投票:0回答:1

我正在为Python的c语言中的代码创建包装器。 C代码基本上在终端中运行,并具有以下主要功能原型:

void main(int argc, char *argv[]){
f=fopen(argv[1],"r");
f2=fopen(argv[2],"r");

所以基本上,读取的参数是终端中的字符串。我创建了以下python ctype包装器,但似乎我使用了错误的类型。我知道从终端传递的参数被读取为字符,但是等效的python侧面包装给出了以下错误:

import ctypes
_test=ctypes.CDLL('test.so')

def ctypes_test(a,b):
  _test.main(ctypes.c_char(a),ctypes.c_char(b))

ctypes_test("323","as21")



TypeError: one character string expected

我已经尝试添加一个字符,只是为了检查共享对象是否被执行,它会像打印命令一样工作,但是会暂时直到共享对象中的代码部分需要文件名。我也试过 ctypes.c_char_p但得到。

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

根据注释中的建议更新至以下内容:

def ctypes_test(a,b):
      _test.main(ctypes.c_int(a),ctypes.c_char_p(b))
ctypes_test(2, "323 as21")

还出现同样的错误。

python ctypes
1个回答
0
投票

在Windows上使用此测试DLL:

#include <stdio.h>

__declspec(dllexport) void main(int argc, char* argv[])
{
    for(int i = 0; i < argc; ++i)
        printf("%s\n",argv[i]);
}

此代码将调用它。 argv基本上是C中的char**,因此ctypes类型是POINTER(c_char_p)。您还必须传递字节字符串,并且它不能是Python列表。它必须是ctypes指针的数组。

>>> from ctypes import *
>>> dll = CDLL('./test')
>>> dll.main.restype = None
>>> dll.main.argtypes = c_int,POINTER(c_char_p)
>>> args = (c_char_p * 3)(b'abc',b'def',b'ghi')
>>> dll.main(len(args),args)
abc
def
ghi
© www.soinside.com 2019 - 2024. All rights reserved.