C++ call python with cmake

cmake python3

vcpkg install python3

cmake file

cmake_minimum_required(VERSION 3.0.0)
project(c++_python VERSION 0.1.0 LANGUAGES C CXX)

# python
find_package(Python3 COMPONENTS Development REQUIRED)

add_executable(c++_python main.cpp)

# libs
target_link_libraries(${PROJECT_NAME} PRIVATE Python3::Python)

1. python as string

#include <Python.h>
int main(int, char**){
    Py_Initialize();
    PyRun_SimpleString("print('hello')");
    Py_Finalize();
    return 0;
}

2. Call python from File

#include<stdio.h>
#include<conio.h>
#include<string>
#include <Python.h>
int main(int, char**){
    std::string filename="../test.py";
    std::wstring wfilename=std::wstring(filename.begin(),filename.end());
    std::wstring mode=L"r";
    FILE* file;
    Py_Initialize();
    file=_Py_wfopen(wfilename.c_str(),mode.c_str());
    // PyRun_SimpleString("print('hello')");
    PyRun_SimpleFile(file,filename.c_str());
    Py_Finalize();
    return 0;
}

3. Call python function

pyhelper.hpp

#ifndef PYHELPER_HPP
#define PYHELPER_HPP
#pragma once

#include <Python.h>

class CPyInstance
{
public:
	CPyInstance()
	{
		Py_Initialize();
	}

	~CPyInstance()
	{
		Py_Finalize();
	}
};

class CPyObject
{
private:
	PyObject *p;
public:
	CPyObject() : p(NULL)
	{}

	CPyObject(PyObject* _p) : p(_p)
	{}

	
	~CPyObject()
	{
		Release();
	}

	PyObject* getObject()
	{
		return p;
	}

	PyObject* setObject(PyObject* _p)
	{
		return (p=_p);
	}

	PyObject* AddRef()
	{
		if(p)
		{
			Py_INCREF(p);
		}
		return p;
	}

	void Release()
	{
		if(p)
		{
			Py_DECREF(p);
		}

		p= NULL;
	}

	PyObject* operator ->()
	{
		return p;
	}

	bool is()
	{
		return p ? true : false;
	}

	operator PyObject*()
	{
		return p;
	}

	PyObject* operator = (PyObject* pp)
	{
		p = pp;
		return p;
	}

	operator bool()
	{
		return p ? true : false;
	}
};

#endif

then call function:

	CPyInstance hInstance;

	//import module
	CPyObject pName = PyUnicode_FromString("pyemb3");
	CPyObject pModule = PyImport_Import(pName);

	if(pModule)
	{
		CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger");
		if(pFunc && PyCallable_Check(pFunc))
		{
			//call func
			CPyObject pValue = PyObject_CallObject(pFunc, NULL);
			printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
		}
		else
		{
			printf("ERROR: function getInteger()\n");
		}
	}
	else
	{
		printf_s("ERROR: Module not imported\n");
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值