鱼C论坛

 找回密码
 立即注册
查看: 1810|回复: 4

请问有Python调用c++的实例参考吗?写的代码C++不识别

[复制链接]
发表于 2019-11-22 16:03:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
RT
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-11-22 16:42:59 From FishC Mobile | 显示全部楼层
       据我所知,C++ 代码必须编译成 .pyd (其实就是 .dll)才能被 Python 程序调用。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-11-22 16:48:28 | 显示全部楼层
jackz007 发表于 2019-11-22 16:42
据我所知,C++ 代码必须编译成 .pyd (其实就是 .dll)才能被 Python 程序调用。

我用的ctypes库调用的c++dll,传的参数总是不识别类型
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-22 21:06:16 | 显示全部楼层
  1. #include <Python.h>
  2. #include <iostream>

  3. PyObject *add(PyObject *self, PyObject *args)
  4. {
  5.         int x, y;
  6.         if(!PyArg_ParseTuple(args, "ii", &x, &y))
  7.                 return NULL;
  8.         return Py_BuildValue("i", x + y);
  9. }

  10. PyObject *sub(PyObject *self, PyObject *args)
  11. {
  12.         int x, y;
  13.         if(!PyArg_ParseTuple(args, "ii", &x, &y))
  14.                 return NULL;
  15.         return Py_BuildValue("i", x - y);
  16. }

  17. PyObject *print(PyObject *self, PyObject *args)
  18. {
  19.         char *str;
  20.         if(!PyArg_ParseTuple(args, "s", &str))
  21.                 return NULL;
  22.         std::cout << str << std::endl;
  23.         return PyBool_FromLong(1);
  24. }

  25. static PyMethodDef hello_methods[] = {
  26.         {"add", add, METH_VARARGS, "add function"},
  27.         {"sub", sub, METH_VARARGS, "sub function"},
  28.         {"print", print, METH_VARARGS, "print function"},
  29.         {NULL, NULL, 0, NULL}
  30. };

  31. static PyModuleDef hello_module = {
  32.         PyModuleDef_HEAD_INIT,
  33.         "hello module",
  34.         NULL,
  35.         -1,
  36.         hello_methods,
  37.         NULL,
  38.         NULL,
  39.         NULL,
  40.         NULL
  41. };

  42. PyMODINIT_FUNC PyInit_hello()
  43. {
  44.         return PyModule_Create(&hello_module);
  45. }
复制代码

  1. g++ -fPIC -shared hello.cpp -I/usr/include/python3.8 -o hello.so
复制代码


参考
https://blog.csdn.net/zong596568821xp/article/details/81133511

linux下我试了,没问题
windows下我还没有试
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-23 12:42:16 | 显示全部楼层
windows下编译

创建 setup.py
  1. from distutils.core import *
  2. setup(
  3.         name="hello",
  4.         version="1.0",
  5.         ext_modules=[Extension("hello", ["hello.cpp"])]
  6. )
复制代码


执行 python setup.py build

参考
https://www.cnblogs.com/xiacaojun/p/9956741.html
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-20 22:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表