Creating a simple c# dll and access it from ruby

2020-04-12 16:49发布

问题:

I'm trying to make my first c# dll. I want to be able to call it's methods/functions from ruby with win32API. I have made this dll:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {

        public int PropA = 10;

        public void Multiply(Int32 myFactor)
        {
            PropA *= myFactor;

        }
    }
}

I compiled it with Visual Studio 2010 and got my ClassLibrary1.dll file.

Now for the ruby part i tried this:

f = "c:/path_to_file/ClassLibrary1.dll"
mult = Win32API.new(f,"Multiply",["I"],"I")

But, i get the following error:

Error: #<RuntimeError: (eval):0:in `initialize': GetProcAddress: Multiply or MultiplyA

To be honest, I never created a dll, nor do I have experience with c#. I just wanted to get started. I have used many dll's with Ruby via win32API before (user32 mostly).

I guess my dll is not ok?

Regards,

回答1:

To consume functions from DLLs as done in a Win32 context, these functions need to be export-visible from the DLL. These functions are usually flagged with dllexport and will show up in the export table of a DLL. You can verify that user32 and other Win32 DLLs do this by using a utility such as dumpbin (MSDN).

dllexport, dllimport @ MSDN

Unfortunately, .NET doesn't have immediate support for making functions export-visible, only for bringing in such functions via the DllImport (MSDN) Attribute.

COM is the easiest way to consume code written within .NET from a non-.NET environment, but if you must use the lower level bindings, you can make an intermediate DLL in C, C++/CLI, or any other language and framework combination that can write export headers to a dll, to call your .NET code.

Also, A few articles exist on making this happen via post-compilation automation or other workarounds, here are a few for your reference.

How to Automate Exporting .NET Function to Unmanaged Programs @ CodeProject

Unmanaged Exports @ Google Sites

DllExport - Provides C-style exports for pure .NET assemblies



回答2:

Without doing anything extra, the DLL created is an Assmebly intended to be run inside the .Net runtime (the CLR).

You can expose it through Com as described in the related question: Can Ruby import a .NET dll? which



标签: c# ruby winapi dll