C# calling a MASM Assembly DLL

1

For the sake of learning, I'm trying to call an Assembly function from C#. I'm working in a very sterile project doing everything as simply as I can. Here's my assembly (mostly cut and paste from codeproject):

.386
.model flat, stdcall
option casemap :none

include \masm32\include\masm32rt.inc

.code
LibMain proc instance:dword,reason:dword,unused:dword 
     mov     eax,1
     ret
LibMain     endp
PrintMess proc
     print "Test"
     exit
PrintMess endp
End LibMain

Note: The assembly builds just fine. No errors and the only warning is that masm32rt.inc has another .model line that the assembler is ignoring, this warning is fine. I've set up my environment using these instructions.

For C#, a language I'm much more familiar with, I've tried 2 main approaches: Reflection and adding the DLL as a reference. Both give me an error saying that an assembly manifest is expected. Here I'm at a lose.

My C# is simply:

Assembly mylib = Assembly.LoadFile(@"C:\mypath\MyLib.dll");

And I get The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018) as an error on that line. I don't know anything about assembly manifests. Any direction towards how to create and embed one would be appreciated.

c#
interop
masm
asked on Stack Overflow Aug 13, 2012 by Corey Ogburn

1 Answer

3

The word "assembly" can mean two things. When you use MASM, assembly means "machine code". When you use .NET, assembly means "container of managed code".

Assembly.LoadXxx() can only load .NET assemblies that were created with .NET tools. it cannot load DLLs that contain pure machine code. You'll need to use pinvoke with the [DllImport] attribute to call the functions in the DLL.

You'd also better check that your DLL actually exports the functions. At the Visual Studio Command Prompt, run dumpbin.exe /exports on your DLL to see the exported names. Some odds that you won't see "PrintMess", you need to pass a .def file to the linker to tell it which functions need to be exported.

answered on Stack Overflow Aug 13, 2012 by Hans Passant

User contributions licensed under CC BY-SA 3.0