python编程__C语言调用Python模块和Python中调用C函数
#include <stdio.h>
int main()
{
Py_Initialize();
printf(“Python_Initialize failed\n”);
return 1;
}
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyRun_SimpleString(“import sys”); //直接执行python语句
PyRun_SimpleString(“sys.path.append('./')”);
pModule = PyImport_ImportModule(“ss”);
if (pModule == NULL) {
printf(“can't import module\n”);
return 1;
}
PyEval_CallObject(pFunc,NULL);
Py_Finalize();
return 0;
}
def hello():
print “hello world”;
[chenbaihu@build17 code_test]$ ./c_py
libc = CDLL('/lib64/libc.so.6');
str = “hello world”;
var = 5;
libc.printf(“%s\t%d\n”, str, var);
#include <vector>
#include <string>
#include <stdio.h>
extern “C” {
int arrinit();
const char* arrtest(int version, const char *main_conf);
}
std::vector<std::string> vec;
int arrinit()
{
vec.push_back(“aaaaa”);
vec.push_back(“bbbb”);
vec.push_back(“cccccc”);
vec.push_back(“dddddd”);
printf(“%s\n”,”arrinit 4″);
return 4;
}
const char* arrtest(int version, const char *main_conf)
{
printf(“%d\t%s\n”, version, main_conf);
return vec[version].c_str();
arr = CDLL('./arr.so')
ret = arr.arrinit(); # 直接调用动态库so中的函数
print ret;
ARRTESTFUN = arr.arrtest # 将so中的函数映射到python中的函数,后面声明输入值列表和返回值列表
ARRTESTFUN.argtypes = [c_int, c_char_p]
ARRTESTFUN.restype = c_char_p
conf = ARRTESTFUN(2, “/home/s/cloudkill/etc/main_conf.json”); # 调用
print conf;
from ctypes import *
f = 'mytest.so'
cdll.LoadLibrary(f)
api = CDLL(f)
api.add.argtypes = [c_int, c_int]
api.add.restype = c_int
api.sub.argtypes = [c_int, c_int]
api.sub.restype = c_int
print api.add(3, 2)
print api.sub(3, 2)
有点像在python中去写接口文件,由于是python的标准库,所以这种方式用的还是蛮多的。
try:
from os.path import abspath
from os.path import dirname
curf_path = dirname(abspath(__file__))
globals()[__NETPROTO_PY_MODULE_NAME] = ctypes.cdll.LoadLibrary(curf_path + '/netproto_pymodule.so')
#print “Load Module: “, globals()[__NETPROTO_PY_MODULE_NAME]
except Exception, e:
print “Load Module <netproto_pymodule.so> Error: “, e
sys.exit(-1)
__NETPROTO_PY_MODULE_NAME = '__netproto_pydll'
__dllmod = globals()[__NETPROTO_PY_MODULE_NAME]
Main = __dllmod.main_main
# CreatePackerHandler
CreatePackerHandler = __dllmod.CreatePackerHandler
CreatePackerHandler.argtypes = [ctypes.c_int, ctypes.c_char_p]
CreatePackerHandler.restype = ctypes.c_int
# DeletePackerHandler
DeletePackerHandler = __dllmod.DeletePackerHandler
DeletePackerHandler.argtypes = [ctypes.c_int]
DeletePackerHandler.restype = ctypes.c_bool
# AddEncryptKey
AddEncryptKey = __dllmod.AddEncryptKey
AddEncryptKey.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
AddEncryptKey.restype = ctypes.c_bool
# Pack func
Pack = __dllmod.Pack
Pack.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int]
Pack.restype = ctypes.c_char_p
# UnPack func
UnPack = __dllmod.UnPack
UnPack.argtypes = [ctypes.c_int, ctypes.c_char_p]
UnPack.restype = ctypes.c_char_p
NS.Main()
def CreatePackerHandler(version, type):
try:
if type!=PACKER_SERVER and type!=PACKER_CLIENT:
print “Un-supported type: “, repr(type)
return None
if version not in (2,9,10):
print “Un-supported version: “, repr(version)
return None
id = NS.CreatePackerHandler(version, type)
__Handler_Map[id] = (version, type)
return id
except Exception, e:
print “CreatePackerHandler Error: “, e
return None
def DeletePackerHandler(handler_id):
try:
version, type = __Handler_Map.get(handler_id, (None, None))
if version is None or type is None:
raise RuntimeError(“Handler Id <%s> NOT Exists.”%handler_id)
ret_bool = NS.DeletePackerHandler(handler_id)
if ret_bool:
__Handler_Map.pop(handler_id, None)
return ret_bool
except Exception, e:
print “DeletePackerHandler Error: “, e
return False
extern “C” {
int main_main(void);
int CreatePackerHandler(int version, const char* role );
bool DeletePackerHandler(int handler_id);
bool AddEncryptKey(int handler_id, int key_id, const char* key_type, const char* key1_p, const char* key2_p);
const char* Pack(int handler_id, char* raw_data_p, int var1, int var2, int key_id);
const char* UnPack(int handler_id, char* packed_data_p);
}
#endif