tags:

views:

298

answers:

3

I'm busy getting to know a tiny bit of C/C++, and interop with C#. I've checked several examples of creating a simple Win32 DLL and using this from C#, but when I try and call into my DLL, I get the runtime error: "Unable to find an entry point named TestFunc". My DLL looks like this, and I created it from a Win32 DLL project, with the empty project option:

Header:

__declspec(dllexport) int TestFunc(char *, char *, char *);

Code file:

#include "stdafx.h"
#include "TestLib.h"

__declspec(dllexport) int TestFunc(char *arg1, char *arg2, char *arg3) 
{
  char str1[] = "Brady Kelly";
  char str2[] = "Hello World";
  char str3[] = "1234567890";

  strcpy(arg1, str1);

  return 128;   
}

What am I doing wrong?

+4  A: 

Is your function compiled using C or C++ bindings? You don't specify, but it looks to me like there is a possibility that you are using the C++ compiler - the compiler uses very different name mangling from the C compiler and you will not be able to find the name "TestFunc" as simply as if you were using the C compiler or using C name mangling rules.

To simply tell the C++ compiler to use C name mangling rules, use this in the header file:

extern "C"
{
  __declspec(dllexport) int TestFunc(char *, char *, char *);
}
1800 INFORMATION
Just shows you, I wasn't even aware of name mangling. Thanks!
ProfK
Exactly what I needed!
Barak C
+2  A: 

Also, you only need the declspec in front of the function declaration (in the header file), not the definition. A useful tool for examining what is exported from the DLL, and what the DLL depends on is Dependency Walker.

anon
+1  A: 

Actually since you have tagged this question as C, I'd suggest a minor change from what 1800 INFORMATION's solution:

#ifdef __cplusplus
extern "C" {
#endif

#ifdef EXPORT_MODE
#define METHODTYPE __declspec(dllexport)
#else 
#define METHODTYPE __declspec(dllimport)
#endif

#ifdef __cplusplus
}
#endif

/*! _The_ method */
METHODTYPE int TestFunc(char *, char *, char *);

This will let you use the same header both in clients' code and your code.

NB: Dependency Walker is no longer bundled with VS2008. You must download it if you are using VS2008.

dirkgently