Question

Hi i know how to make Library (dll) in windows with visual studio 2012 with c++ and import in python with ctypes work great

here small example

lib.cpp

#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT int sum(int a,int b)
{
return (a+b);
}

lib.h

int sum(int,int); 

test.py

from ctypes import *
mydll=cdll.LoadLibrary('lib.dll')
print mydll.sum(2,2)

i try run same code in mac with xcode 4.4 version when i buld in xcode i get warring message

__declspec attribute 'dllexport' is not supported

and when import lib.dylib in python i get error

AttributeError: dlsym(0x101afba30, sum): symbol not found

what i do wrong ? can some one write simple code how i can make a dylib in mac with xcode correct to import with Ctypes in python 2.6.4

OR

the are is better way to import libaries in python in both system for mac and win ?

basic i like to write code in windows with visual studio 2012 make dll i and then simple compiler in mac with xcode and import in python

Was it helpful?

Solution

Your problem was that you already had the dylib loaded into your Python interpreter. Just rebuilding it won't affect what you have loaded into memory.

Just doing another LoadLibrary may or may not re-load the library, and there's no way to force it to do so.

There is also no way to unload and reload libraries in ctypes. The main reason is that there is no safe way to do so on all platforms—in fact, before 10.4, OS X itself was such a platform. (And Python still has current source code in the tree to support pre-10.4 OS X in ctypes.) But also, trying to come up with a model that does things the safe way on every platform isn't exactly trivial. So, ctypes doesn't try.

If you really need to do it, the _ctypes module underneath ctypes generally exports the necessary functions into Python. If you know the names for your platform, you can find them with help(_ctypes), or by looking at the source.

Briefly, on most modern POSIX platforms (including OS X 10.5+) it's _ctypes.dlclose(mydll._handle), while on Win32, it's _ctypes.FreeLibrary(mydll._handle). In either case, if you ever use mydll again (or any functions or values that you were referencing from it), you should pray for a segfault. You may also segfault on exit. And on Windows, it may not actually free the library when you ask it to, and in some cases you have to ask the library if it's ready to unload before you can do so, and there are threading complexities, and… well, just read the FreeLibrary docs on MSDN, and of course the manpage for dlclose(3) on every POSIX system you care about.

In general, it's a much better idea to just start up a new interpreter process instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top