简体   繁体   中英

How do I call method C# Dll method using RegAsm?

I created a C# Dll that use "Register for com interop" and I managed to register it using RegAsm:

RegAsm.exe -tlb -codebase MathLib.dll

After that I got the message:

"Assembly exported to 'C:\\Test\\MathLib.tlb', and the type library was registered successfully"

How do I call now the methods inside the Dll? For example it has a public function:

int Add(int a, int b) { return a + b; }

that adds 2 numbers and return the result. How do I call it from the command-line and see the result of the operation?

Thanks very much.

How does it work?

Create a new classlibrary or proceed with an existing one. Then add the UnmanagedExports Nuget package.

This is pretty much all setup that is required.

Now you can write any kind of static method, decorate it with [DllExport] and use it from native code. It works just like DllImport, so you can customize the marshalling of parameters/result with MarshalAsAttribute.

During compilation, my task will modify the IL to add the required exports.

A good example would be the following lines:

class Test
{
  [DllExport("Add", CallingConvention = CallingConvention.Cdecl)]
  public static int Add(int a, int b)
  {
     return a + b;
  } 
}

As you know, keep registering your lib with RegAsm. To import your COM function back on another project, you shall Marshall it like a native method, declaring it in your code with the [DLLImport] attribute.

References:

Unmanaged Exports

UnmanagedExports Nuget package

I hope that helped in someway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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