混合编程:VS2017 C++相互调用Python3.X类/对象/函数/DLL调用等笔记【Windows】

 

python3 api 文档: https://docs.python.org/3/library/

栗子工程 均在 github 中:https://github.com/linqingwudiv1/CppCallPythonExample

 Note:测试Python 需要先编译一下DLL

内容:

  •  C++调用python脚本 

  •  python脚本调用C++ DLL/SO

-----------------------------------------------------割割割割割割-----------------------------------------------------------

 C++调用python脚本 :

Q1:安装Python:

  下载地址:https://www.python.org/downloads/windows/

  note:

    注意x86和x64平台,根据计算机类型选择,否则会报平台不兼容问题.

    必须勾选DownLoad Debug Binaries 

    否则必然会报link1104 找不到phthon3_d.lib 

  

Q2:C++工程配置:

    

   

 

  

   Note:必须把DLL放到项目根目录去(是项目根路径,不是解决方案根路径),否则运行 会报找不到Python.dll 错误

 

Q3:代码:

  逻辑:C++生成一个Python类,并调用成员方法.返回结果。

  .py部分:

    

class math:
    def __init__(self):
        self.test = '<test>'
    def add(self, num1, num2):
        print (self)
        print ("add functin start:", self.test)
        print (num1 + num2)

        print ("add functin end:<", self.test + ">")
        return num1 + num2

    def subtract(self, num1, num2):
        print (self)
        print ("sub functin :")
        print (num1 - num2)
        return num1 - num2

  .cpp部分:

// CppCallPython.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>

#include "Python.h"
using namespace std;
int main()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    if (!Py_IsInitialized())
    {
        printf("初始化失败!");
        return 0;
    }

    PyObject * pModule = NULL;
    PyObject * pFunc = NULL;
    PyObject* pDict = NULL;
    PyObject* pClass = NULL;
    PyObject* pIns = NULL;

    pModule = PyImport_ImportModule("hello");
    assert(pModule != NULL);

    pDict = PyModule_GetDict(pModule);
    assert(pDict != NULL);

    pClass = PyDict_GetItemString(pDict, "math");
    assert(pClass != NULL);

    pIns = PyObject_CallObject(pClass, nullptr);
    assert(pIns != NULL);

    auto result = PyObject_CallMethod(pIns, "add", "(ii)", 1, 2);
    //PyObject_New();

    std::cout << "<finished>";
    Py_DECREF(pIns);
    Py_Finalize();
    std::cout << "Hello World!
"; 
}

-----------------------------------------------------割割割割割割-----------------------------------------------------------

python调用C++ DLL/SO :

Q1:关于本机调试:

  如果希望debuger程序(C++ DLL),需要在VS python项目中启用本机代码调试:

QQ:完整代码:

 c++ .cpp部分

using namespace std;
extern "C" {
    __declspec(dllexport) char* HiPython(char* msg);
    __declspec(dllexport) int HiPythonInt(int b);
}

char* HiPython(char* msg)
{
    cout << "[output on cpp] from python message : " << msg << endl;
    
    char ret_c[] = "c++callback [i like 拆腻子]";
    return ret_c;
}

int HiPythonInt(int b) 
{
    cout << "[output on cpp] from python message : 系数:"<< b << endl;

    return 5 * b;
}

Python 部分:

import sys, platform
import ctypes, ctypes.util
from ctypes import cdll

lib = None

if platform.system() == "Windows":    
    print(f"hello python on Windows")
    lib = cdll.LoadLibrary("./dll/cppdll.dll")
elif platform.system() == "Linux":
    lib = cdll.LoadLibrary("./so/cppdll.so")
    print(f"hello python on Linux")
else:
    print(f"unknown platform.")
if lib != None:
    lib.HiPython.argtypes = [ctypes.c_char_p]
    lib.HiPython.restype = ctypes.c_char_p
    teststr = bytes("i am 拆腻子","utf8")
    ret_str = lib.HiPython(teststr).decode("utf8")
    ret_int = lib.HiPythonInt(3);
    print("HiPythonInt return : ", ret_int, "|    HiPython Return:" , ret_str)
else:
    print("input any key and enter exit:")
print("input any key and enter exit:")
input()
原文地址:https://www.cnblogs.com/linqing/p/10905044.html