tags:

views:

67

answers:

3

I have successfully gotten Dreamweaver to accept my DLL and call it's methods. The DLL is written in C++ with C interpeted functions (so function names aren't mangled.)

I would like to become comfortable with C++ pointers and datatype, but I have a much stronger proficiency with C# so for our timeline I think it's worthwhile to investigate alternatives to a straight C solution.

Would I theoretically be able to build a DLL in C# that would be seen from the "outside" the same as a C DLL?

and as an alternative

Would I be able to "wrap" a C# DLL with the working C DLL?

The main part of my concern is the datatypes of the functions, as when dreamweaver calls them it is expecting void and char pointers as the format for passing data back and forth.

Thank you.

+7  A: 

Contrary to popular belief, this is possible.
See here.

SLaks
Wow! I learn something every day. Thanks for this.
Will Dean
+1  A: 

You can create a COM wrapper around a .NET DLL. I am using this now to call .NET functions from some older C/C++ code.

0A0D
+4  A: 

Yes, the C++/CLI compiler makes this easy to do. It automatically generates a "thunk" that ensures that the CLR gets loaded when an unmanaged program calls an exported function. Best demonstrated with an example.

Starting with the C# code, create a new project from the Class Library project template. You'll have to write a static method, necessary because C code doesn't know anything about classes. Here's a simple example:

using System;

namespace ClassLibrary1 {
    public static class Mumble {
        public static int method(int arg) { return arg; }
    }
}

Right-click the solution name in the Solution Explorer window, Add + New Project. Select Visual C++, CLR, Class Library. Right-click the new project, Properties, Common Properties, Framework and References, click Add New Reference. Projects tab, select your C# project.

Open the .cpp file and write code like this:

#include "stdafx.h"

using namespace ClassLibrary1;

extern "C" __declspec(dllexport)
int method(int arg) {
    return Mumble::method(arg);
}

Build. This DLL can now be used by your unmanaged code, it can call the "method" function. Both this DLL and your C# DLL need to be copied to the directory of the unmanaged program.

Beware that there's overhead in calling this method. The thunk that the C++/CLI compiler generates does a fair amount of work to ensure that the CLR is loaded and initialized. Debugging is going to be unfun (use Debugger.Break()) and uncaught managed exceptions will crash your program with a very poor diagnostic.

Hans Passant
Great answer. Thank you.
Josh