简体   繁体   English

C#调用MASM程序集DLL

[英]C# calling a MASM Assembly DLL

For the sake of learning, I'm trying to call an Assembly function from C#. 为了学习,我试图用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 ): 这是我的程序集(主要是从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. 没有错误,唯一的警告是masm32rt.inc有另一个汇编程序忽略的.model行,这个警告没问题。 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. 对于C#,我更熟悉的一种语言,我尝试了两种主要方法:反射并添加DLL作为参考。 Both give me an error saying that an assembly manifest is expected. 两者都给我一个错误,说明了一个程序集清单。 Here I'm at a lose. 我在这里输了。

My C# is simply: 我的C#简单地说:

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

And I get The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018) 我得到The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018) The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018) as an error on that line. The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)作为该行的错误。 I don't know anything about assembly manifests. 我对装配清单一无所知。 Any direction towards how to create and embed one would be appreciated. 任何关于如何创建和嵌入一个方向的方向都将受到赞赏。

The word "assembly" can mean two things. “汇编”这个词可能意味着两件事。 When you use MASM, assembly means "machine code". 使用MASM时,汇编表示“机器代码”。 When you use .NET, assembly means "container of managed code". 使用.NET时,程序集意味着“托管代码的容器”。

Assembly.LoadXxx() can only load .NET assemblies that were created with .NET tools. Assembly.LoadXxx()只能加载使用.NET工具创建的.NET程序集。 it cannot load DLLs that contain pure machine code. 它无法加载包含纯机器代码的DLL。 You'll need to use pinvoke with the [DllImport] attribute to call the functions in the DLL. 您需要使用带有[DllImport]属性的pinvoke来调用DLL中的函数。

You'd also better check that your DLL actually exports the functions. 您还可以更好地检查您的DLL实际导出函数。 At the Visual Studio Command Prompt, run dumpbin.exe /exports on your DLL to see the exported names. 在Visual Studio命令提示符下,在DLL上运行dumpbin.exe / exports以查看导出的名称。 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. 你不会看到“PrintMess”的一些可能性,你需要将.def文件传递给链接器,告诉它需要导出哪些函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM