Search code examples
c#c++dllpinvokemarshalling

Trying to import a c++ dll to a c-sharp code


I'm trying to make the most simple example, just so that I begin to understand how this is done. Searching the web I only found examples I don't quite understand.

This is the c++ code, in a C++ class library project.

#include "stdafx.h"
#include <iostream>
#include "ClassLibrary1.h"
using namespace std;

extern "C" { 
    void CallMe()
    {
        cout << "I am the called function! Hooray!" << endl;
    }
}

This is the C# Console application code:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("calling dll");
            CallMe();
            Console.ReadLine();
        }

        [DllImport("ClassLibrary1.dll")]
        public static extern void CallMe();
    }
}

I added the dll as a reference to the C# project, and also placed it in the same folder as the executable.

Still I get an "Unable to load DLL "ClassLibrary1.dll": the specified module could not be found (exception from HRESULT: 0x8007007E)".

What am I missing?

I tried adding "__declspec(dllexport)" before the declaration of CallMe in the C++ code, but no luck.


Solution

  • (Posted on behalf of the OP).

    The solutions were, respectively:

    Still I get an "Unable to load DLL "ClassLibrary1.dll": the specified module could not be found (exception from HRESULT: 0x8007007E)".

    Mistake #1: wrong placement of dll, sorry.

    Now I get a new error: "An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)"

    Mistake #2: c++ code was compiled as x86, instead of x64, double sorry.

    I now get the error: "Unable to find entery point named "CallMe" in dll"

    Mistake #3: you must put "__declspec(dllexport)" when declaring/defining the function.