0

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."

DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
  • You can't just add a reference to a non .NET dll library. You need to use PInvoke. Read more here: http://msdn.microsoft.com/en-us/magazine/cc164123.aspx – lahsrah Mar 07 '14 at 03:15

1 Answers1

2

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

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • You can use C++/CLI in order to write C++ managed code that can be imported as a normal .NET dll library from a C# project. http://stackoverflow.com/questions/10223186/c-cli-wrapper-for-native-c-to-use-as-reference-in-c-sharp – thepirat000 Mar 07 '14 at 04:32