[英]How can I call an Assembly procedure from C# and get a result back?
I'm trying to call a very simple Assembly procedure from C# to get something returned from it.我正在尝试从 C# 调用一个非常简单的组装过程,以从中返回一些东西。
Here's the C# code:这是 C# 代码:
class Program
{
static void Main(string[] args)
{
ulong test = Start();
Console.WriteLine(test);
}
[DllImport(@"C:\dev\masm\basic.dll")]
private static extern ulong Start();
}
Here's the Assembly (MASM) code:这是汇编(MASM)代码:
.code
Start proc
mov rax, 1
ret
Start endp
end
I assemble and link from the console with the following command:我使用以下命令从控制台组装和链接:
ml64 basic.asm /link /subsystem:console /entry:Start /out:basic.dll /dll /machine:x64
What's really interesting is that I'm able to successfully call a simple Assembly procedure that prints "Hello, World."真正有趣的是,我能够成功调用打印“Hello, World”的简单组装过程。 but doesn't return anything, However, when I try to call this procedure, even though I do specify an entry point in the DLL: I still get this error:但不返回任何内容,但是,当我尝试调用此过程时,即使我在 DLL 中指定了一个入口点:我仍然收到此错误:
System.EntryPointNotFoundException: 'Unable to find an entry point named 'Start' in DLL 'C:\dev\masm\basic.dll'.'
I'm most likely missing something, but I can't figure it out.我很可能错过了一些东西,但我无法弄清楚。
You were so close.你是如此接近。 You need to mark the procedure as an export.您需要将该过程标记为导出。
.code
Start proc export
mov rax, 1
ret
Start endp
end
Console.WriteLine(test);
now prints 1
.现在打印1
。
You can verify that the Start
procedure is exported by using a dev console and running DUMPBIN /HEADERS <DLL>
and seeing it in the export section您可以通过使用开发控制台并运行DUMPBIN /HEADERS <DLL>
并在导出部分中看到它来验证Start
过程是否已导出
File Type: DLL
Section contains the following exports for basic.dll
00000000 characteristics
FFFFFFFF time date stamp
0.00 version
1 ordinal base
1 number of functions
1 number of names
ordinal hint RVA name
1 0 00001000 Start
Summary
1000 .rdata
1000 .text
An aside: the error you were getting旁白:你得到的错误
System.EntryPointNotFoundException: 'Unable to find an entry point named 'Start' in DLL 'C:\dev\masm\basic.dll'.'
doesn't actually have to do with the entry point of the dll (often called Main) but it's a PInvoke term that basically means "Hey, we couldn't find that exported "Start" method you told us to look for."实际上与 dll(通常称为 Main)的入口点无关,但它是一个 PInvoke 术语,基本上意味着“嘿,我们找不到您告诉我们要查找的导出的“开始”方法。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.