简体   繁体   中英

Creating a CPP DLL for use in a C# program

So I have a WPF solution. I added a new project and added a CPP Dll project to it.

I used this example. Pretty straight forward.

http://www.codeproject.com/Articles/9826/How-to-create-a-DLL-library-in-C-and-then-use-it-w

Here is my code

CppTestDll.cpp

#include <stdio.h>

extern "C"
{
    __declspec(dllexport) void DisplayHelloFromDLL()
    {
        printf("Hello from DLL !\n");
    }
}

When I build this I do in fact get a DLL

Now when I go into my WPF app and attempt to add a reference to this DLL I get this error.

"A reference to 'C:\\DIR\\testcppdll.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component."

If you look in the example you cite:

Creating a simple C# application:

  • Start Visual Studio .NET. Go to File->New->Project.
  • Select Visual C# Project. ... (you can select WPF Project)
  • Give the name to your application. Press OK. Into the specified class, insert the following two lines:

[DllImport("TestLib.dll")] public static extern void DisplayHelloFromDLL ();

In C#, keyword extern indicates that the method is implemented externally.

Your code should look something like this:

using System;
using System.Runtime.InteropServices;     // DLL support

class HelloWorld
{
    [DllImport("TestLib.dll")]
    public static extern void DisplayHelloFromDLL ();

    public  void SomeFunction()
    {
        Console.WriteLine ("This is C# program");
        DisplayHelloFromDLL ();
    }
}

You don't add a reference to the to the DLL - you P/Invoke the Function using DLLImport

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