Created
May 6, 2014 21:53
-
-
Save serge1/33bcfd38c7b8735047ff to your computer and use it in GitHub Desktop.
Using a C++ DLL from Python by involving ctypes package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifdef _MSC_VER | |
#define _SCL_SECURE_NO_WARNINGS | |
#define _CRT_SECURE_NO_WARNINGS | |
#endif | |
#include <string> | |
#include <sstream> | |
#include <string.h> | |
#include "DllTest.h" | |
__declspec( dllexport ) | |
int | |
doubler( int i ) | |
{ | |
return 2 * i; | |
} | |
__declspec( dllexport ) | |
int | |
triple( int i ) | |
{ | |
return 3 * i; | |
} | |
__declspec( dllexport ) | |
void | |
triple_str( int i, char* buffer, int* len ) | |
{ | |
std::stringstream ss; | |
ss << "Triple of " << i << " equal to " << 3 * i; | |
strncpy( buffer, ss.str().c_str(), *len ); | |
*len = ss.str().size(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import ctypes | |
if (sys.platform == "win32"): | |
libname = "Release/DllTest.dll" | |
else: | |
libname = "libDllTest.so" | |
lib = ctypes.cdll.LoadLibrary(libname) | |
print(lib.doubler(3)) | |
print(lib.triple(6)) | |
len = ctypes.c_int(200) | |
s = ctypes.create_string_buffer(len.value) | |
lib.triple_str(7, s, ctypes.byref(len)) | |
print(repr(s.value)) | |
print(len.value) | |
len = ctypes.c_int(200) | |
lib.triple_str(10, s, ctypes.byref(len)) | |
print(repr(s.value)) | |
print(len.value) | |
len = ctypes.c_int(200) | |
lib.triple_str(1000, s, ctypes.byref(len)) | |
print(repr(s.value)) | |
print(len.value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "DllTest.h" | |
#define BUFFER_SIZE 200 | |
int main() | |
{ | |
std::cout << doubler( 2 ) << std::endl; | |
std::cout << triple( 3 ) << std::endl; | |
char buffer[BUFFER_SIZE]; | |
int buffer_len = BUFFER_SIZE; | |
triple_str( 4, buffer, &buffer_len ); | |
std::cout << buffer << " and len = " << buffer_len << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment