LMC008
LMC008

Reputation: 53

Calling DLL using C#

typedef struct
{
    // The contents of this struct are platform-dependent and subject to
    // change. You should not manipulate the contents of this struct directly.

    /*New stuff*/
//  HWND            m_hWnd;
//  HDEVNOTIFY      m_hDevNotify;

} fdGlove;


FGLOVEAPI fdGlove *fdOpen(char *pPort, bool bOnlyAllowSingleConnection = false);    
FGLOVEAPI int   fdClose(fdGlove *pFG);
FGLOVEAPI int   fdGetGloveHand(fdGlove *pFG);
FGLOVEAPI int   fdGetGloveType(fdGlove *pFG);

I have a DLL file called fglove.dll and I need using C# to call it. I have written code like this:

    [StructLayout(LayoutKind.Sequential)]
    public class fdGlove
    { 

    }
    [DllImport("fglove.dll")]
    public static extern fdGlove fdOpen(string pPort, bool bOnlyAllowSingleConnection);

but when I debug the program it is has an error (Unable to find an entry point named 'fdOpen' in DLL 'fglove.dll'.)

Can someone point out what I have done wrong?

Upvotes: 0

Views: 482

Answers (3)

Yaur
Yaur

Reputation: 7452

look at the name of the exported symbol in Dependency Walker. More than likely it will be _fdImport or something similar and you will need to update your DLLImportAttribute to match the exported name.

Upvotes: 0

selbie
selbie

Reputation: 104514

fdOpen is using a default parameter - which can only mean you are trying to export a C++ function out of a DLL. The result is that "fdOpen" is getting "name mangled" in the export table as something that looks like "fdOpen@YAXPB_W0I@Z".

You're better off exporting this function as C. Declare and define fdOpen as follows:

extern "C" fdGlove* __stdcall fdOpen(char* pPort, bool bOnlyAllowSingleConnection);

Other possible issues:

  1. The DLL isn't in the same directory as the EXE trying to load it.

  2. You forgot to export the function from the DLL. You need to use a .DEF file or the __declspec(dllexport) attribute on the function definition. Use "dumpbin /exports fglove.dll" to figure out if this is the case.

  3. Confusion between stdcall and cdecl compile options. I get it confused, so try replacing "_stdcall" with "_cdecl" above. Or try it without either attribute.

Upvotes: 3

Richard Schneider
Richard Schneider

Reputation: 35477

The compiler of fglove is most likely doing so type of name mangling.

Use DUMPBIN fglove.dll to get the real names.

Then use [DllImport("fglove.dll", EntryPoint='...')] where ... is the real name.

Upvotes: 1

Related Questions