问题
I composed .Net 3.5 dll with single method, which is to be called by Delphi .exe. Unfortunately it does not work.
The steps: 1. Create C# 3.5 dll with the code:
public class MyDllClass
{
public static int MyDllMethod(int i)
{
MessageBox.Show("The number is " + i.ToString());
}
}
- Go to Assembly Properties --> Assembly Information and checked the "Make Assembly COM-Visible"
- Used RegAsm.exe to register my dll
This throws Delphi exception which indicates it cannot connect the dll. What are the steps required to enabled usage of C# managed dll from unmanaged code.
Does any one familiar with good example about the subject?
Thank you
回答1:
You may have more luck skipping the COM part by using my project template for unmanaged exports
class MyDllClass
{
[DllExport]
static int MyDllMethod(int i)
{
MessageBox.Show("The number is " + i.ToString());
return i + 2;
}
}
In Delphi, you'd import it like so:
function MyDllMethod(i : Integer) : Integer; stdcall; extern 'YourAssembly.dll';
I had to vote your question down, though. For not even caring as much as to provide code that would compile. (your C# method doesn't return a value, yet it expects as int)
回答2:
After massive investigation I found the solution: it's all about registration parameters. The flag /codebase must be added to the regasm command.
Many posts out there suggest to use Guid and other COM attributes on the C# Com exposed object, I managed to deliver COM functionality using the ComVisible(true) attribute and regasm /tlb /codebse command.
The code:
[Guid("7DEE7A79-C1C6-41E0-9989-582D97E0D9F2")]
[ComVisible(true)]
public class ServicesTester
{
public ServicesTester()
{
}
//[ComVisible(true)]
public void TestMethod()
{
MessageBox.Show("You are in TestMEthod Function");
}
}
and as I mentioned I used regasm.exe /tlb /codebase to register it
回答3:
One thing that could be a problem if you made your assembly x64 or AnyCPU. Since Delphi is 32 bit (x86) you need to make your assembly x86 or make sure regasm.exe registers it also in the 32 bits registry. You do that by using the x86 version of regasm.exe.
回答4:
You should learn more about the tools you are using. You try to connect two quite different worlds (.Net, Delphi) using yet another (not too simple) technology: COM. Your question shows quite clear that you don't have a good understaning of COM and probably not of .Net. There is no simple example which solves exactly your use case. You have to learn COM, than you have to learn how to make .Net code available to COM and then you have to learn how to call COM objects from Delphi. That IS already the shortcut. No further shortcuts are available!
来源:https://stackoverflow.com/questions/6174584/call-c-sharp-dll-from-delphi