用ctypes调用argc / argv函数 [英] Calling argc/argv function with ctypes

查看:167
本文介绍了用ctypes调用argc / argv函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a wrapper to a code in c for Python. The c code basically runs in terminal and has the following main function prototype:

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

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

So basically arguments read are strings in terminal. I created following python ctype wrapper, but it appears I am using wrong type. I know the arguments passed from the terminal is read as characters but an equivalent python side wrapper is giving following error:

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 但得到。

I have tried adding one character, just to check if shared object gets executed, it does as print commands work but momentarily till the section of the code in shared object needs file name. I also tried ctypes.c_char_p but get.

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






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


Updated as per the suggestion in the comments to the following:

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

却出现相同的错误。

推荐答案

针对Windows使用此测试DLL:

Using this test DLL for Windows:

#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指针的数组。

This code will call it. argv is basically a char** in C, so the ctypes type is POINTER(c_char_p). You also have to pass bytes strings and it can't be a Python list. It has to be an array of ctypes pointers.

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

这篇关于用ctypes调用argc / argv函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆