0

I have written a C# application which needs to call a function in a C++ dll on a button click. But on cllicking the button, it throws 'EntryPointNotFound' Exception.

Below is the code snippet of C#
    public class Test
    {
        [DllImport("Demo.dll", EntryPoint = "OpenFile"]
        public static extern bool OpenFile(string fileName);
    }
private void button1_Click_1(object sender, EventArgs e)
        {
            bool check = Test.OpenFile("test.txt"); // exception thrown at this point
            if (check)
            {
                // Not entering this area.. 
            }
        }


C++ Header (.h file)

__declspec(dllexport) bool OpenFile(CString fileName);

Cpp class (.cpp )
__declspec(dllexport) bool Demo::OpenFile(CString fileName)
{
        return true;
}

Please help.

Rakesh J
  • 41
  • 6
  • Check the exports table of the DLL you're using. I suspect you're running into name-mangling issues (even though it's a free-function). – Dai May 15 '15 at 17:46
  • Also, use the correct `[MarshalAs]` attributes. The CLR doesn't know that `fileName` is a `CString` instead of `char*` or `std::string`. The same applies for the return value, by default .NET `Boolean` is marshalled as Win32 `BOOL` instead of C++ `bool`. – Dai May 15 '15 at 17:47
  • You also can't p/invoke a CString. You'll have to change your method to take a char* or wchar*. http://stackoverflow.com/questions/7618130/pinvoke-with-a-cstring – shf301 May 15 '15 at 18:29
  • I changed the entry point as the function name found in DependencyWalker. Added a function without any paramters. That worked.!!! But it is displays {"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."} when using string as parameter. I changed the C++ method parameter to char*. But still it is not working – Rakesh J May 15 '15 at 20:01

1 Answers1

0

Basically you need to add extern "C" to the dll code:

extern "C" __declspec(dllexport) bool OpenFile(CString fileName);

Also see stackoverflow question

Community
  • 1
  • 1
Nicko Po
  • 727
  • 5
  • 21
  • I used the below code : extern "C" __declspec(dllexport) bool OpenFile(CString fileName); But still doesn't worked – Rakesh J May 15 '15 at 18:35