python3 api 文檔: https://docs.python.org/3/library/python
栗子工程 均在 github 中:https://github.com/linqingwudiv1/CppCallPythonExampleios
Note:測試Python 須要先編譯一下DLLc++
內容:git
-----------------------------------------------------割割割割割割-----------------------------------------------------------github
下載地址:https://www.python.org/downloads/windows/windows
note:api
注意x86和x64平臺,根據計算機類型選擇,不然會報平臺不兼容問題.app
必須勾選DownLoad Debug Binaries 函數
不然必然會報link1104 找不到phthon3_d.lib 測試
邏輯: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!\n"; }
-----------------------------------------------------割割割割割割-----------------------------------------------------------
若是但願debuger程序(C++ DLL),須要在VS python項目中啓用本機代碼調試:
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()