2

I am trying to call a C++ function from python. I tried this example but don't get it working.

When I try to compile in cmd.exe on Windows: g++ -shared -c -fPIC function.cpp -o function.o, I get a warning: -fPIC ignored for target (all code is position independent). I don't know whether this is an important flag in the first place?

My function.o appears, and I compile: g++ -shared -Wl,-soname,library.so -o library.so function.o to make it a shared library. The file library.so appears.

Then I run my wrapper:

import ctypes
print ctypes.windll.library.square(4)

Upon which this error appears:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-    packages\spyderlib\widgets\externalshell\sitecustomize.py", line 523, in runfile
    execfile(filename, namespace)
  File "C:\Users\Renger\untitled14.py", line 2, in <module>
    print ctypes.windll.library.square(4) # windows
  File "C:\Python27\lib\ctypes\__init__.py", line 435, in __getattr__
    dll = self._dlltype(name)
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] Can't find given module 

My python program and the library.so file are saved in the same directory.

Am I missing something obvious here?

Best!

Community
  • 1
  • 1
renger
  • 775
  • 1
  • 7
  • 11
  • The .so extension is Unix-specific, on Windows you need .dll instead. Find a tutorial which explains how to do it on Windows. – pts May 11 '14 at 10:58
  • If you write a Python extension (as an alternative to using an existing DLL with `ctypes`), you may want to use distutils (https://docs.python.org/2/distutils/) to build the .dll for you. – pts May 11 '14 at 11:00
  • 1
    Unless you're using a cross compiler, g++ probably created a COFF object file and linked a PE DLL. So you can probably just rename the output file to "library.dll". When linking, use `-o library.dll` and remove `-Wl,-soname,library.so` since that's ignored anyway. – Eryk Sun May 11 '14 at 17:54
  • That said, you may be better off using the Windows SDK and Visual Studio 2010 Express. Microsoft frowns on [linking to msvcrt.dll](http://msdn.microsoft.com/en-us/library/abx4dbyh%28v=vs.100%29.aspx) ("It is intended for future use only by system-level components."); clearly it [annoys Raymond Chen](http://blogs.msdn.com/b/oldnewthing/archive/2014/04/11/10516280.aspx). – Eryk Sun May 11 '14 at 18:01
  • Thanks, doing it in Visual Studio is indeed much easier. The nice step-by-step manual [here](http://wolfprojects.altervista.org/articles/dll-in-c-for-python/), really helped me out. – renger May 11 '14 at 18:49

0 Answers0