当前位置:首页 » 编程语言 » python调用c程序

python调用c程序

发布时间: 2024-10-22 04:54:32

A. python 调用c++程序, c++程序如何返回数组给python

C/C++不能直接返回一个数组。这是由于在C/C++中,数组不是一种类型,因此不能被直接返回。
一般有两种方法来返回一个数组。
第一种方法:
返回一个指向数组的指针,例如char (*retArray)[10]声明了一个函数retArray,该函数可以返回指向具有10个char元素的数组
第二种方法:
如果你不喜欢用指针的形式返回数组,那么可以采用返回一个结构的形式。这种形式相对较安全,可以避免忘记释放指针而造成内存泄露,也可以避免访问悬挂指针造成的错误。但缺点是由于结构是先拷贝再返回,因此如果结构较大时,会影响效率和占用较大内存。
这是C的限制,Python调用C也是这种情况

B. Windows下如何在python中调用c语言程序编译的dll

这个dll可能是用borland公司的编译器编译出来的。 或者这个dll可能不是在你本机上编译的,如果你有这个dll的源码,可以编译一下,然后放到脚本同一目录下,再试试。

C. python嵌套C语言、调用外部C的dll,python实参如何传递并修改

handle = ctypes.c_int(0)
ret = lib.XF_OpenDev(0, ctypes.byref(handle))

handle作为指针传进去后如果被改掉,返回的是一个c_int 或者c_long, 你可以通过handle.value来获得可以在python中灵活运用的真正的python整形

D. python怎么调用c的动态链接库

Python调用C/C++动态链接库的需求
在自动化测试过程中,难免会遇到语言混合使用的情况,这不,我们也遇到了。初步决定采用Robot Framework作为自动化测试框架后,其支持Java和Python,而Python作为主流的语言,怎么能放弃使用它的机会^_^。 然而产品采用是古老90年代开发的C/S结构,因为古老,当时也没有考虑到对产品的测试进行自动化,Client端并没有预留CLI(Command Line interface)形式的接口,真是雪上加霜啊。
那怎么自动化?采用AutoIT来对客户端界面进行自动化测试?可惜AutoIT对当初开发采用的控件识别不是很好,如果采用控件所在位置来进行控制的方式,又会导致自动化测试并不是很稳定。那么!!!只有自己开发接口了,目前在Client端开发出CLI形式的接口,将其封装为DLL,然后在Robot FrameWork框架中采用Python对DLL进行调用。任务艰巨哪!
Python调用DLL例子
示例一
首先,在创建一个DLL工程(本人是在VS 2005中创建),头文件:
[cpp] view plain 在CODE上查看代码片派生到我的代码片//hello.h
#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif
extern "C"
{
HELLO_API int IntAdd(int , int);
}
CPP文件:
[cpp] view plain 在CODE上查看代码片派生到我的代码片//hello.cpp
#define EXPORT_HELLO_DLL
#include "hello.h"
HELLO_API int IntAdd(int a, int b)
{
return a + b;
}
这里有两个注意点:
(1)弄清楚编译的时候函数的调用约定采用的__cdecl还是__stdcall,因为根据DLL中函数调用约定方式,Python将使用相应的函数加载DLL。
(2)如果采用C++的工程,那么导出的接口需要extern "C",这样python中才能识别导出的函数。
我的工程中采用__cdecl函数调用约定方式进行编译链接产生hello.dll,然后Python中采用ctypes库对hello.dll进行加载和函数调用:
[python] view plain 在CODE上查看代码片派生到我的代码片from ctypes import *
dll = cdll.LoadLibrary('hello.dll');
ret = dll.IntAdd(2, 4);
print ret;
OK,一个小例子已经完成了,如果你感兴趣,但还没试过,那就尝试一下吧。
示例二
示例一只是一个"hello world"级别的程序,实际运用中更多的需要传递数据结构、字符串等,才能满足我们的需求。那么这个示例将展示,如何传递数据结构参数,以及如何通过数据结构获取返回值。
首先编写DLL工程中的头文件:
[cpp] view plain 在CODE上查看代码片派生到我的代码片//hello.h
#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif
#define ARRAY_NUMBER 20
#define STR_LEN 20
struct StructTest
{
int number;
char* pChar;
char str[STR_LEN];
int iArray[ARRAY_NUMBER];
};
extern "C"
{
//HELLO_API int IntAdd(int , int);
HELLO_API char* GetStructInfo(struct StructTest* pStruct);}
CPP文件如下:
[cpp] view plain 在CODE上查看代码片派生到我的代码片//hello.cpp
#include <string.h>
#define EXPORT_HELLO_DLL
#include "hello.h"
HELLO_API char* GetStructInfo(struct StructTest* pStruct){
for (int i = 0; i < ARRAY_NUMBER; i++)
pStruct->iArray[i] = i;
pStruct->pChar = "hello python!";
strcpy (pStruct->str, "hello world!");
pStruct->number = 100;
return "just OK";
}
GetStructInfo这个函数通过传递一个StructTest类型的指针,然后对对象中的属性进行赋值,最后返回"just OK".
编写Python调用代码如下,首先在Python中继承Structure构造一个和C DLL中一致的数据结构StructTest,然后设置函数GetStructInfo的参数类型和返回值类型,最后创建一个StructTest对象,并将其转化为指针作为参数,调用函数GetStrcutInfo,最后通过输出数据结构的值来检查是否调用成功:
[python] view plain 在CODE上查看代码片派生到我的代码片from ctypes import *
ARRAY_NUMBER = 20;
STR_LEN = 20;
#define type
INTARRAY20 = c_int * ARRAY_NUMBER;
CHARARRAY20 = c_char * STR_LEN;
#define struct
class StructTest(Structure):
_fields_ = [
("number", c_int),
("pChar", c_char_p),
("str", CHARARRAY20),
("iArray", INTARRAY20)
]
#load dll and get the function object
dll = cdll.LoadLibrary('hello.dll');
GetStructInfo = dll.GetStructInfo;
#set the return type
GetStructInfo.restype = c_char_p;
#set the argtypes
GetStructInfo.argtypes = [POINTER(StructTest)];objectStruct = StructTest();
#invoke api GetStructInfo
retStr = GetStructInfo(byref(objectStruct));#check result
print "number: ", objectStruct.number;
print "pChar: ", objectStruct.pChar;
print "str: ", objectStruct.str;
for i,val in enumerate(objectStruct.iArray):
print 'Array[i]: ', val;
print retStr;
总结
1. 用64位的Python去加载32位的DLL会出错
2. 以上只是些测试程序,在编写Python过程中尽可能的使用"try Except"来处理异常3. 注意在Python与C DLL交互的时候字节对齐问题4. ctypes库的功能还有待继续探索

E. python调用c函数

Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过
1. Python 调用 C (base)
想在python中调用c函数, 如这儿的fact
#include <Python.h>

int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}

PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;

if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};

void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}

把这段代码存为wrapper.c, 编成so库,
gcc -fPIC wrapper.c -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)

2. Python 调用 C++ (base)
在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,
#include <Python.h>

class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};

int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}

int fact(int n)
{
TestFact t;
return t.fact(n);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;

if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}

static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};

extern "C" //不加会导致找不到initexample
void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}

把这段代码存为wrapper.cpp, 编成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)

3. Python 调用 C++ (Boost.Python)
Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.
http://dev.gameres.com/Program/Abstract/Building%20Hybrid%20Systems%20with%20Boost_Python.CHN.by.JERRY.htm
首先在ubuntu下安装boost.python, apt-get install libboost-python-dev
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}

BOOST_PYTHON_MODULE(hello)
{
using namespace boost::python;
def("greet", greet);
}

把代码存为hello.cpp, 编译成so库
g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1

此处python路径设为你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查

然后在有此so库的目录, 进入python, 可以如下使用
>>> import hello
>>> hello.greet()
'hello, world'

4. python 调用 c++ (ctypes)
ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.
http://python.net/crew/theller/ctypes/

#include <Python.h>

class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};

int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}

extern "C"
int fact(int n)
{
TestFact t;
return t.fact(n);
}
将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config

进入python, 可以如下使用
>>> import ctypes
>>> pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12

F. 【python-C相互调用】python里的dict如何作为参数传入.so中的c语言函数

#include<stdio.h>
#include<stdlib.h>
#include<Python.h>

staticPyObject*
wmf_reverse(PyObject*self,PyObject*args,PyObject*kwargs){
staticchar*kwlist[]={"name",NULL};
char*name=NULL;
PyObject*retval=NULL;

//问题1:只取一个字符串,format应该是"s"
//>>>if(PyArg_ParseTupleAndKeywords(args,keyds,"isi",kwlist,&name))
if(PyArg_ParseTupleAndKeywords(args,kwargs,"s",kwlist,&name)){
retval=(PyObject*)Py_BuildValue("i",1);
printf("%s ",name);
//问题2:不要释放
//>>>free(name);
}else{
retval=(PyObject*)Py_BuildValue("i",0);
}
returnretval;
}

staticPyMethodDef
wmf_methods[]={
{"reverse",(PyCFunction)wmf_reverse,METH_VARARGS|METH_KEYWORDS,"reverse"},
//问题3:方法定义表,应该用一条空记录来表示结束。
{NULL,NULL,0,NULL},
};

//问题4:没有定义mole
staticstructPyMoleDef
wmf_mole={
PyMoleDef_HEAD_INIT,
"wmf",/*nameofmole*/
NULL,/*moledocumentation,maybeNULL*/
-1,/*sizeofper-interpreterstateofthemole,
or-.*/
wmf_methods,
};

//问题5:入口函数要声明为:PyMODINIT_FUNC
PyMODINIT_FUNC
PyInit_wmf(void){
//问题6:Py_InitMole要初始化的是模块,不是方法。所以传方法定义是错误的。
//另外,python2.x是用Py_Init_mole,python3.x改用PyMole_Create了。
//两者略有差别,自己注意一下吧。这里我用的是python3.x。
//Py_InitMole("wmf",ExtestMethods);
PyObject*m;
m=PyMole_Create(&wmf_mole);
if(m==NULL){
returnNULL;
}
returnm;
}

G. 如何让python调用C和C++代码

如何让python调用C和C++代码

安装python后,会有一个chm格式的python手册。要搞明白如何让python调用C/C++代码(也就是写python的 extension),你需要征服手册中的
<<Extending && embedding>>厚厚的一章。在昨天花了一个小时看地头晕脑胀,仍然不知道如何写python的extension后,查阅了一些其他 书籍,最终在<<Python Programming On Win32>>书中找到了教程。
下面记录一下如何在visual studio 2005中,写一段C/C++的MessageBox代码,然后提供后python调用,最后的结果当然是显示一个MessageBox.
1. 首先要明白的是,所谓的python扩展(也就是你提供给python的c/c++代码,不一定是c/c++代码,可以是其他语言写的代码)是一个 dll,并且这个dll放在本机python安装目录下的DLLs目录下(譬如我机器上的路径是:F:\Program Files\Python25\DLLs),假如我们接下来要写的扩展mole名为mb,python调用的代码为: import mb
mb.showMsg("Python's really amazing, I kindda love it!")
python怎么找到我们的mb模块呢?就是上面说的,我们要生成一个mb.dll,然后拷贝到Dlls目录下面,为了区别普通的dll和python专用扩展的dll,我们的 mb.dll修改成mb.pyd(python dll)
2. 搭建环境,我们要使用python提供的c头文件和lib库来进行扩展的开发。 在vs 2005下点击菜单 "工具"->"选项", 打开选项对话框,选择"项目和解决方案->VC++目录", 然后在右边"显示以下内容的目录"得comboBox上选择"包含文件”,添加python的include目录(我的机器上是"F:\Program
Files\Python25\include"),然后选择库文件,添加python的libs目录(我的机器上是"F:\Program Files\Python25\libs")。
既然扩展是一个dll,接下来我们要建立一个“动态链接库”工程,然后开始写代码:
#include <python.h> //python.h是包含python一些定义的头文件,在python的include目录下 /*
我的python版本是2.5, 因为安装python后它没提供debug下的lib库文件,因此你必须生成release版的dll,
想要生成dll版本的,你要到python官网上自己去下载python源代码,当然你可以继续生成release版本的dll,但dll中包含调试信息

*/
#pragma comment(lib, "python25.lib")
//先不管
static PyObject* mb_showMsg(PyObject* self, PyObject *args); /*
如果你的扩展是mb,那么必须实现一个initmb函数,并且从dll中导出这个函数,但我们在python中调用import mb时,python会去dll里去调用
initmb函数,这个函数告诉python我们有些什么函数,该怎么告诉python我们有一个showMsg函数呢?下面详解 */
//必须extern "C"下,这样不会在C++编译器里不会更改掉导出的函数名字,我第一次就犯了这样的错误
extern "C" __declspec(dllexport) void initmb() { /*
当调用mb.showMsg("Python's really amazing, I kindda love it!")时, 相当于你告诉python我有一个showMsg函数,我们怎么告诉python去调用我们dll里的mb_showMsg函数呢?技巧就是下面的方式, 定义一个字典数据结构,key => showMsg, value =>mb_showMsg,METH_VARARGS是函数调用方式,仔细查手册吧 */
static PyMethodDef mbMethods[] = { {"showMsg", mb_showMsg, METH_VARARGS},
{NULL, NULL, NULL} /*sentinel,哨兵,用来标识结束*/ };
//告诉python我们的模块名叫mb, 模块包含的函数都在mbMethods字典里 PyObject *m = Py_InitMole("mb", mbMethods); } /*
接下来实现核心功能showMsg */
//第一个self参数我们用不着,具体查手册,第二个参数是python传给我们的参数,它是一个python的参数tuple
static PyObject* mb_showMsg(PyObject* self, PyObject *args) {
//我们的showMsg函数需要的是一个字符串参数 const char* msg = NULL; /*

调用特殊参数解码python传递给我们的参数,s是string,我们传递接收参数的变量地址,
如果你的功能函数需要两个参数,在PyArg_parseTuple后面继续添加接受参数的变量地址,
这个函数的原型是类似printf的不定参数的形式
PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...); */
if (!PyArg_ParseTuple(args, "s", &msg)) return NULL;
//调用MB
int r = ::MessageBox(NULL, "hello", "Caption:Form C mole", MB_ICONINFORMATION | MB_OK);
//返回值
return Py_BuildValue("i", r); }
将上面这段混杂着大量注释的代码拷贝到你的编辑器里,然后编译生成mb.dll,修改后缀成mb.pyd,然后拷贝到python的DLLs目录下,打开idle(python的交互程序),写入代码: import mb
mb.showMsg("Python's really amazing, I kindda love it!")
可以看到弹出来一个MessageBox。

热点内容
长安unik选哪个配置更好 发布:2024-10-22 08:18:25 浏览:687
二手车怎么查看具体车型配置 发布:2024-10-22 08:09:51 浏览:475
php设置不超时 发布:2024-10-22 07:53:51 浏览:330
unity塔防源码 发布:2024-10-22 07:48:20 浏览:312
安卓手机日常如何管理不卡顿 发布:2024-10-22 07:43:50 浏览:6
网络存储选择什么服务器 发布:2024-10-22 07:43:38 浏览:496
求生之路2怎么建服务器 发布:2024-10-22 07:24:11 浏览:817
php源码安装卸载 发布:2024-10-22 07:24:07 浏览:523
服务器搭建端口 发布:2024-10-22 07:23:35 浏览:872
用C程序算法 发布:2024-10-22 07:23:35 浏览:407