zoukankan      html  css  js  c++  java
  • Python调用C代码

    Python的ctypes模块可以直接调用c/c++导出的函数,将c/c++编译成动态连接库后可供python直接调用。

    如下代码,将导出2个函数:

    #include <iostream>
    #include <windows.h>
    
    using namespace std;
    
    extern "C" __declspec(dllexport) int Add(int a, int b);
    extern "C" __declspec(dllexport) void Echo(char str[]);
     
    BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
    {
        return TRUE;
    }
    __declspec(dllexport) int Add(int a, int b)
    {
    	int c = a + b;
    	return c;
    }
    
    __declspec(dllexport) void Echo(char str[])
    {
    	cout << str << endl;
    	return;
    }
    

      

    编译为dll,命令如下:

    K:DropboxcodecppProject1Project1>cl -LD test.cpp
    用于 x64 的 Microsoft (R) C/C++ 优化编译器 17.00.61030 版
    版权所有(C) Microsoft Corporation。保留所有权利。
    
    test.cpp
    C:Program Files (x86)Microsoft Visual Studio 11.0VCINCLUDExlocale(336) : wa
    rning C4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc
    Microsoft (R) Incremental Linker Version 11.00.61030.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:test.dll
    /dll
    /implib:test.lib
    test.obj
       正在创建库 test.lib 和对象 test.exp
    

      

    在python中调用:

    import os
    from ctypes import *
    
    test = cdll.LoadLibrary(os.getcwd() + '/test.dll')
    print test
    print test.Add(1, 2)
    test.Echo("hartnett_test")

    调用成功后输出:

    K:Dropboxcode	est>python 1.py
    <CDLL 'K:Dropboxcode	est/test.dll', handle fabe0000 at 235beb8>
    3
    hartnett_test
    

      

  • 相关阅读:
    ES6 随记(1)-- let 与 const
    this 机制的四种规则
    BEM(一种 CSS 命名规则)
    WebSocket 的后记
    WebSocket 初体验
    “空”的艺术-当数据为空时显示什么
    前端路由以及浏览器回退,hash & history & location
    体验 WebFont,网页上的艺术字
    dedecms安装全过程(集成环境)
    面向对象(五)
  • 原文地址:https://www.cnblogs.com/awakenjoys/p/python_call_c.html
Copyright © 2011-2022 走看看