zoukankan      html  css  js  c++  java
  • Windows系统Python直接调用C++ DLL

    环境:Window 10,VS 2019, Python 2.7.12, 64bit

    1,打开 VS 2019,新建C++ Windows 动态链接库工程 Example,加入下列文件,如果Python是64位的则在VS中 Solution platforms 选择 x64 编译成64位的 DLL;

    Example.h

     1 #pragma once
     2 
     3 #ifndef CPP_EXPORTS
     4 #define CPP_EXPORTS
     5 #endif
     6 
     7 #ifdef CPP_EXPORTS
     8 #define CPP_API _declspec(dllexport)
     9 #else 
    10 #define CPP_API _declspec(dllimport)
    11 #endif
    12 
    13 #include <iostream>
    14 using namespace std;
    15 
    16 #ifdef __cplusplus
    17 extern "C"
    18 {
    19 #endif
    20 
    21     CPP_API int __cdecl getInt();
    22     CPP_API const char* __cdecl getString();
    23     CPP_API void __cdecl setString(const char* str);
    24 
    25 #ifdef __cplusplus
    26 }
    27 #endif

    Example.cpp

     1 #include "pch.h"
     2 #include "Example.h"
     3 
     4 CPP_API int __cdecl getInt()
     5 {
     6     return 5;
     7 }
     8 
     9 CPP_API const char* __cdecl getString()
    10 {
    11     return "hello";
    12 }
    13 
    14 CPP_API void __cdecl setString(const char* str)
    15 {
    16     cout << str << endl;
    17 }

    编译,得到 Example.dll

    2, 打开 Command,cd 到 Example.dll 所在目录,输入 Python2,进入python环境

    >>> from ctypes import *
    >>> dll = CDLL("Example.dll")
    >>> print dll.getInt()
    5

    >>> getStr = dll.getString
    >>> getStr.restype = c_char_p
    >>> pChar = getStr()
    >>> print c_char_p(pChar).value
    hello

    >>> setStr = dll.setString
    >>> setStr.argtypes = [c_char_p]
    >>> pStr = create_string_buffer("hello")
    >>> setStr(pStr)
    hello
    -1043503984

  • 相关阅读:
    高效并发服务器模型
    Linux下Wiki服务器的搭建
    Wiki程序PmWiki的安装和汉化
    Linux 套接字编程中的 5 个隐患
    IOCP简介
    IP协议详解之IP地址要领
    IP协议详解之配套协议:ARP, ICMP
    超级详细Tcpdump 的用法
    如何测试主机的MTU多大?
    Linux下Socket编程的端口问题( Bind error: Address already in use )
  • 原文地址:https://www.cnblogs.com/gujf2016/p/11282352.html
Copyright © 2011-2022 走看看