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:\Dropbox\code\cpp\Project1\Project1>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.0\VC\INCLUDE\xlocale(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:\Dropbox\code\test>python 1.py
<CDLL 'K:\Dropbox\code\test/test.dll', handle fabe0000 at 235beb8>
3
hartnett_test

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM