[ACCEPTED]-Python: accessing DLL function using ctypes -- access by function *name* fails-attributeerror

Accepted answer
Score: 12

Your C++ compiler is mangling the names 12 of all externally visible objects to reflect 11 (as well as their underlying names) their 10 namespaces, classes, and signatures (that's 9 how overloading becomes possible).

In order 8 to avoid this mangling, you need an extern "C" on 7 externally visible names that you want 6 to be visible from non-C++ code (and therefore 5 such names cannot be overloaded, nor in 4 C++ standard can they be inline, within 3 namespaces, or within classes, though some 2 C++ compilers extend the standard in some 1 of these directions).

Score: 11

All is working now :) To summarize your 5 posts:

Write DLL in C++:

// Header
extern "C"
{   // Name in DLL will be "MyAdd" - but you won't be able to find parameters etc...
    __declspec(dllexport) int MyAdd(int a, int b);
}  
// Name will be with lot of prefixes but some other info is provided - IMHO better approach
__declspec(dllexport) int MyAdd2(int a, int b);

//.cpp Code
__declspec(dllexport) int MyAdd(int a, int b)
{   return a+b;
}
__declspec(dllexport) int MyAdd2(int a, int b)
{   return a+b;
} 

Then you can use 4 program link.exe to see real function name 3 in dll. link.exe is for example in MSVC2010 2 here:

c:\program files\microsoft visual studio 10.0\VC\bin\link.exe

use:

link /dump /exports yourFileName.dll

you see Something like:

ordinal hint RVA      name
      1    0 00001040 ?MyAdd2@@YAHHH@Z = ?MyAdd2@@YAHHH@Z (int __cdecl MyAdd2(int,int))
      2    1 00001030 MyAdd = _MyAdd

Then in 1 python you can import it as:

import ctypes

mc = ctypes.CDLL('C:\\testDll3.dll')

#mc.MyAdd2(1,2) # this Won't Work - name is different in dll
myAdd2 = getattr(mc,"?MyAdd2@@YAHHH@Z") #to find name use: link.exe /dump /exports fileName.dll 
print myAdd2(1,2)
#p1 = ctypes.c_int (1) #use rather c types
print mc[1](2,3) # use indexing - can be provided using link.exe

print mc.MyAdd(4,5)
print mc[2](6,7) # use indexing - can be provided using link.exe
Score: 7

Perhaps because the C++ name is mangled 3 by the compiler and not exported from the 2 DLL as RingBell. Have you checked that it appears 1 in the exported names exactly like that?

More Related questions