//.h文件
#include <Python.h>
//.cpp文件
//C/C++ my.so 或者my.dll
enter "C" void printHello()
{
std::cout<<"Hello World"<<std::endl;
}
#Python
import ctypes
from ctypes import *
loadso = ctypes.cdll.LoadLibrary
mylib = loadso("./my.so")
mylib.printHello()
>>>Hello world
//.h文件
#include <Python.h>
//.cpp文件
enter "C" int printHello(const char* str)
{
std::cout<<str<<std::endl;
return 1;
}
str = create_string_buffer(b"Hello World")
#mylib.printHello("Hello World") 这里死活就是显示:H,*(str+4)才是'e',*(str+8) 是'l' 依次类推
print (mylib.printHello(str))
>>>Hello World
>>>1
#由于对Python不是特别的熟悉 怎么也做不到显示C++返回的字符串, Python只能显示C++返回的字符串子能看到一个地址而已
//.h文件 本来这是C++连接Mysql 我只摘抄部分代#include <Python.h>
//.cpp文件
//传递多个参数 Python传过来的参数在args里面
PyObject* printfHello(PyObject* self,PyObject* args)
{
int i=0
const char* str;
if (!PyArg_ParseTuple(args, "i|s", &i,&str)) //i 表示整形 s 表示字符串
return PyLong_FromLong(0);
print("%d,%s",i,str);
return Py_BuildValue("s","OK"); //向Python返回OK字符串
}
//映射 知道MFC的一看就懂
static PyMethodDef MyMethods[] = {
{"printfHello", printfHello, METH_VARARGS, //"printHello" 中可调用的函数 METH_VARARGS :带有参数 METH_NOARGS:无参数
"print"}, //说明
{"connect", connect, METH_VARARGS,
"connect mysql"},
{NULL, NULL, 0, NULL}
};
static PyObject* UtilError;
// 向Python中注册模块
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"libMysqlUtil", //模块名字 import libMysqlUtil
"C++ Connect Mysql",
-1,
MyMethods
};//PyInit_libMysqlUtil 注意名字 一定要PyInit_ 加上你的模块名字 不然Python import 会提示没有定义 PyInit_你的模块名字 PyMODINIT_FUNC PyInit_libMysqlUtil(void) { PyObject* m = nullptr; m = PyModule_Create(&spammodule);
//m= Py_InitModule(....) Python 2.7 if(!m) { return m; } UtilError = PyErr_NewException("Util.error",NULL,NULL); Py_INCREF(UtilError); PyModule_AddObject(m,"error",UtilError); return m; }
#python import libMysqlUtil libMysqlUtil.printHello(1,"hello World") >>>1,hello World >>>OK
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-3 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.yuanmawang.com) 版权所有