Skip to content

Instantly share code, notes, and snippets.

@serge1
Created May 6, 2014 21:53
Show Gist options
  • Save serge1/33bcfd38c7b8735047ff to your computer and use it in GitHub Desktop.
Save serge1/33bcfd38c7b8735047ff to your computer and use it in GitHub Desktop.
Using a C++ DLL from Python by involving ctypes package
#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();
}
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)
#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