Loading dll using Python Ctypes -
i've looked @ example given here ctypes - beginner , followed same steps different bit of c code. i've built .dll , .lib using c code given here: http://wolfprojects.altervista.org/articles/dll-in-c-for-python/
//test.c __declspec(dllexport) int sum(int a, int b) { return + b; }
in wrapper.py have this:
import ctypes testlib = ctypes.cdll("c:\\users\\xyz\\documents\\python\\test.dll")
when run script error:
self._handle = _dlopen(self._name, mode)
oserror: [winerror 193] %1 not valid win32 application
if use
testlib = ctypes.libraryloader("c:\\users\\xyz\\documents\\python\\test.dll")
then don't error on running script. if try this:
testlib.sum(3,4)
i error:
dll = self._dlltype(name)
typeerror: 'str' object not callable
the dll , .py in same folder. can me understand what's going on here. i've spent hours trying figure out, have hit wall. thanks.
make sure compiler , version of python both 32-bit or both 64-bit. can't mix, cause of oserror: [winerror 193] %1 not valid win32 application
.
next, make sure compile c program , not c++. that's cause of name mangling mention in answer.
example (note compiler x86 not x64:
c:\>cl /ld /w4 test.c microsoft (r) c/c++ optimizing compiler version 17.00.61030 x86 copyright (c) microsoft corporation. rights reserved. test.c microsoft (r) incremental linker version 11.00.61030.0 copyright (c) microsoft corporation. rights reserved. /out:test.dll /dll /implib:test.lib test.obj creating library test.lib , object test.exp
now use 32-bit python:
c:\>py -2 python 2.7.13 (v2.7.13:a06454b1afa1, dec 17 2016, 20:42:59) [msc v.1500 32 bit (intel)] on win32 type "help", "copyright", "credits" or "license" more information. >>> ctypes import * >>> lib = cdll('test') >>> lib.sum(2,3) 5
if compile c++, can still call functions exporting them c, prevents c++ name mangling:
//test.cpp extern "c" __declspec(dllexport) int sum(int a, int b) { return + b; }
Comments
Post a Comment