6

I'm attempting a very basic interoperation between the 2 languages. I basically have some performance intensive code I wanna handle in C++ and then get the result back to my application.

All is going to be compiled in Visual Studio.

i have chosen int to be the input and output type since marshalling can be a bit wonky and not really what i'm dealing with.

C++ i have:

#include "stdafx.h" // default from vs2013, no idea what it is

_declspec(dllexport) int Diu(int p) {
    return p * 2;
}

C# i have:

using System;

namespace Interop {
    public class Program{
        [System.Runtime.InteropServices.DllImport("Hardworker.dll")]
        public static extern int Diu(int p);

        private static void Main(string[] args) {
            Console.WriteLine(Diu(2));
        }
    }
}

So it's a pretty basic example. But I'm getting the exception:

An unhandled exception of type 'System.BadImageFormatException' occurred in Interop.exe

Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

The C++ project is created as a Console Application > Dll in the create dialog. I checked the C++ dll in the disassembler and i can see a Diu as an exported symbol.

Uh. What did I miss about the setting up interop?

1
  • (or future reader) In addition to taking care to match platform (x86 vs x64, native C++ doesn't support AnyCPU), and name mangling, take care to also match the calling convention between the C++ code and the p/invoke declaration. Commented Jan 24, 2022 at 16:53

1 Answer 1

6

When you get this error: HRESULT: 0x8007000B is caused by platform incompatibility.
Check that that your compiler profile are set to the same platform(x86, x64 or AnyCPU).

Sign up to request clarification or add additional context in comments.

3 Comments

Nice. I my computer is x64. I set compile to x86. And the error changed to EntryPointNotFoundException: Unable to find an entry point named 'Diu' in DLL 'Hardwork.dll'.
@CyberFox C++ mangles the function names based on parameter types, and other qualifiers of the function. You need to declare the function extern "C" for it to export with the name without mangling.
@YngveHammesrland that actually worked. 2 answers in 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.