Ant4res
Ant4res

Reputation: 1225

How to use a C dll within a c# program

I have a .c and a .h file modified to be used within a cpp application, in fact they have the

#ifdef __cplusplus
       extern "C"{
#endif 

prepocessor lines. I was wondering if and how I can use the functions defined there within a c# program. Maybe I have to create a dll for that piece of code?

Upvotes: 0

Views: 258

Answers (3)

Jamie Keeling
Jamie Keeling

Reputation: 9966

Here's a simple example taken from MSDN:

using System;
using System.Runtime.InteropServices;

class PlatformInvokeTest
{
    [DllImport("msvcrt.dll")]
    public static extern int puts(string c);
    [DllImport("msvcrt.dll")]
    internal static extern int _flushall();

    public static void Main() 
    {
        puts("Test");
        _flushall();
    }
}

This assumes you are willing to compile your existing code into a .DLL

Upvotes: 1

Kevin
Kevin

Reputation: 562

You guys don't seem to get it - he doesn't have a dll, he has c++ source files:

You have two options

  1. Translate the c++ code to C# and incorporate it directly into your application

  2. Use a c++ compiler to create a dll from the source files and use PInvoke to access it

As far as if you need to modify the c++ code to create the dll or make it accessable from C#, we have no way of knowing without a posting of the full code.

Upvotes: 1

Here's a clearly example on MSDN blog. You can use IntPtr to load DLL path.

http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx

Upvotes: 0

Related Questions