c和python混合编程_python与C、C++混编的四种⽅式(⼩
结)
混编的含义有两种,
⼀种是在python⾥⾯写C
⼀种是C⾥⾯写python
本⽂主要是进⾏简化,⽅便使⽤。
>>>>>>>>>>>>>>>>>>#
第⼀种、Python调⽤C动态链接库(利⽤ctypes)
pycall.c
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
#include
#include
int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
pycall.py
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./libpycall.so")
lib.foo(1, 3)
print '***finish***'
运⾏⽅法:
gcc -o libpycall.so -shared -fPIC pycall.c
python pycall.py
第2种、Python调⽤C++(类)动态链接库(利⽤ctypes)
pycallclass.cpp
#include
using namespace std;
class TestLib
{
void display();
void display(int a);
};
void TestLib::display() {
cout<<"First display"<
}
void TestLib::display(int a) {
cout<<"Second display:"<
}
extern "C" {
TestLib obj;
void display() {
obj.display();
}
void display_int() {
obj.display(2);
}
}
pycallclass.py
import ctypes
so = ctypes.cdll.LoadLibrary
编程先学c语言还是pythonlib = so("./libpycallclass.so")
print 'display()'
lib.display()
print 'display(100)'
lib.display_int(100)
运⾏⽅法:
g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp python pycallclass.py
第3种、Python调⽤C和C++可执⾏程序
main.cpp
#include
using namespace std;
int a = 10, b = 5;
return a+b;
}
int main()
{
cout<<"---begin---"<
int num = test();
cout<<"num="<
cout<<"---end---"<
}
main.py
import commands
import os
main = "./testmain"
if ists(main):
rc, out = statusoutput(main)
print 'rc = %d, \nout = %s' % (rc, out)
print '*'*10
f = os.popen(main)
data = f.readlines()
f.close()
print data
print '*'*10
os.system(main)
运⾏⽅法(只有这种不是⽣成.so然后让python⽂件来调⽤):
g++ -o testmain main.cpp
python main.py
第4种、扩展Python(C++为Python编写扩展模块)(超级⿇烦的⼀种)Extest2.c
#include
#include
#include
if (n < 2) return(1);
return (n)*fac(n-1);
}
char *reverse(char *s)
{
register char t,
*p = s,
*q = (s + (strlen(s) - 1));
while (s && (p < q))
{
t = *p;
*p++ = *q;
*q-- = t;
}
return(s);
}
int test()
{
char s[BUFSIZ];
printf("4! == %d\n", fac(4));
printf("8! == %d\n", fac(8));
printf("12! == %d\n", fac(12));
strcpy(s, "abcdef");
printf("reversing 'abcdef', we get '%s'\n", \ reverse(s));
strcpy(s, "madam");
printf("reversing 'madam', we get '%s'\n", \ reverse(s));
return 0;
}
#include "Python.h"
static PyObject *
int num;
if (!PyArg_ParseTuple(args, "i", &num))
return NULL;
return (PyObject*)Py_BuildValue("i", fac(num)); }
static PyObject *
Extest_doppel(PyObject *self, PyObject *args) {
char *orig_str;
char *dupe_str;
PyObject* retval;
if (!PyArg_ParseTuple(args, "s", &orig_str)) return NULL;
retval = (PyObject*)Py_BuildValue("ss", orig_str, dupe_str=reverse(strdup(orig_str)));
free(dupe_str);
return retval;
}
static PyObject *
Extest_test(PyObject *self, PyObject *args)
{
test();
return (PyObject*)Py_BuildValue("");
}
static PyMethodDef
ExtestMethods[] =
{
{ "fac", Extest_fac, METH_VARARGS }, { "doppel", Extest_doppel, METH_VARARGS }, { "test", Extest_test, METH_VARARGS },
{ NULL, NULL },
};
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论