Access a method from a DLL from C# program

前端 未结 3 1683
名媛妹妹
名媛妹妹 2020-12-10 07:46

I have a C program and i have created a DLL file. I am using Windows Vista, and Visual C++.

Now I need to access a method from that DLL, from the Main() method of a

相关标签:
3条回答
  • 2020-12-10 08:20

    You're looking for Platform Invoke and the [DllImport] attribute.

    0 讨论(0)
  • 2020-12-10 08:26

    You need to read up on P/Invoke aka pinvoke aka "Platform Invoke":

    http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

    0 讨论(0)
  • 2020-12-10 08:27

    See using a class defined in a c++ dll in c# code which has a great accepted answer. And as Hans Passant wrote in the comments, you cannot add a native DLL as a reference to a C# project.

    When I refer to one of my own native DLLs, I usually either add a dependency between the C# project and the project which generates the native DLL, or I add the DLL as a linked content file in the C# project, like so:

    1. Right-click on the project and choose Add > Existing Item.
    2. Browse and select the DLL you want, but don't click Add yet.
    3. Click on the tiny arrow at the right of the Add button and select Add As Link.
    4. Select the DLL that now appears in your C# project and go to its properties.
    5. Make sure you have Build Action set to Content.

    This will copy the DLL to the bin\Debug folder of the C# project and make sure that, if you once decide to create a Setup project, you can easily reference all content files and include them in the Microsoft Installer package.

    Now, to be able to see the functions written in your native DLL, you have to take care of exporting them (see Exporting C Functions for Use in C or C++ Language Executables and Exporting from a DLL Using __declspec(dllexport)). So you'd have to add an extern "C" block around your function declaration (I am assuming you wrote your code in a .cpp source file and this means that the compiler will emit mangled function names if you do not declare them as being extern "C"):

    extern "C"
    {
        __declspec (dllexport) void __cdecl Foo(const char* arg1);
    }
    
    ...
    
    void Foo(const char* arg1)
    {
        printf ("Hello %s !", arg1);
    }
    

    The __declspec (dllexport) decoration means that the compiler/linker will have to make the function visible from outside of the DLL. And the __cdecl defines how parameters will be passed to the function (the standard "C" way of doing this).

    In your C# code, you'll have to refer to your DLL's exported methods:

    class Program
    {
        [DllImport("mydll.dll")]
        internal static extern void Foo(string arg1);
    
        static void Main()
        {
            Program.Foo ("Pierre");
        }
    }
    

    You should read the Platform Invoke Tutorial which gives all the gory details.

    0 讨论(0)
提交回复
热议问题