zoukankan      html  css  js  c++  java
  • c/c++再学习:C与Python相互调用

    c/c++再学习:Python调用C函数

    Python 调用C函数比较简单
    这里两个例子,一个是直接调用参数,另一个是调用结构体
    C代码

    typedef struct {
    	int i1;
    	int i2;
    	char str[20];
    } core_data_t;
    
    __declspec(dllexport) int add(int a, int b)
    {
    	return a + b;
    }
    
    __declspec(dllexport) int multi(int a, int b)
    {
    	return a * b;
    }
    
    __declspec(dllexport) int struct_add(core_data_t* data)
    {
    	printf("%s
    ", data->str);
    	return data->i1 + data->i2;
    }
    

    python代码

    from ctypes import *
    
    core = CDLL('core.dll')
    
    add_val = core.add(1, 2)
    multi_val = core.multi(2, 3)
    
    print(add_val)
    print(multi_val)
    
    class CoreData(Structure):
        _fields_ = [("i1", c_int),
                    ("i2", c_int),
                    ("str", c_char*20)]
    
    coredata = CoreData()
    coredata.i1 = 10
    coredata.i2 = 20
    coredata.str = b"hello world"
    coredata_ptr = byref(coredata)
    struct_add_val = core.struct_add(coredata_ptr)
    
    print(struct_add_val)
    

    结果

    3
    6
    30
    hello world
    

    C调用python函数

    c调用python,需要在增加<Python.h>和python36.lib,有时遇到编译时需要python36_d.lib时,只需要将python36.lib复制重命名为python36_d.lib放在同目录下即可

    python代码

    def py_print():
        print("py_print")
    
    def py_add(a,b):
        return a+b
    

    c代码

    #include "stdio.h"
    #include "windows.h"
    #include <Python.h>   
    
    void main()
    {
    	Py_Initialize();                  
    	PyObject* pModule = NULL;        
    	PyObject* pFunc = NULL;        
    	PyObject* pArgs = NULL;
    	PyObject* pValue = NULL;
    
    	pModule = PyImport_ImportModule("python_demo");          
    	pFunc = PyObject_GetAttrString(pModule, "py_print");   
    	PyEval_CallObject(pFunc, NULL);   
    
    	pFunc = PyObject_GetAttrString(pModule, "py_add");
    	pArgs = PyTuple_New(2);
    
    	PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5));
    	PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 10));
    
    	pValue = PyEval_CallObject(pFunc, pArgs);
    	int res = 0;
    	PyArg_Parse(pValue, "i", &res);
    	printf("res %d
    ", res);
    
    	Py_Finalize();   
    	return;
    }
    

    结果

    py_print
    res 15
    
  • 相关阅读:
    ASP.NET Web API 记录请求响应数据到日志的一个方法
    EF删除集中方法对比
    CSS 的优先级机制[总结]
    sql备份命令
    sql两张表关联更新字段
    VSCode隐藏node_modules目录
    C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic
    模拟退火(转)
    HNOI2006-鬼谷子的钱袋
    HNOI2006-公路修建问题(二分答案+并查集)
  • 原文地址:https://www.cnblogs.com/langzou/p/8982426.html
Copyright © 2011-2022 走看看