Calling mamaged C# code from Visual C

  • Thread starter Thread starter Tim Nelson
  • Start date Start date
T

Tim Nelson

Hi,
I've got a legacy application written in C. I'd like to evolve the product
(as opposed to completely rewriting it) by adding new features using C#. Is
this possible? I know I should be able to call a managed-code DLL from C,
but I am unsure of the best way to do it, and also how I might marshal the
data between the two parts between the managed and unmanaged parts of the
application.
Can anyone point me in a direction?
Thanks.
 
We had a similar problem. We wanted ActiveX code written in Visual Studio 6
to communicate with a WebService in .NET.

The way we solved it was to create a Managed C++ dll that was also a regular
dll. Use the wizards to create a regular dll, then enable the support for
managed extensions.

The VS6 code calls functions in this dll which in turn calls the WebService.
The limitation of using a regular dll is that you can only use C types, no
CStrings. Since your code is written in C, this should not be a problem.

When implementing this we had a problem freeing memory allocated within the
DLL. From what I could understand, the runtime tracks which CRT the memory
was allocated on. In our case I think the managed DLL used VS.NET version
and the ActiveX used VS6.
In order to overcome this, we created a method called FreeMemory() in the
DLL, this frees the memory in the context of the DLL.


Chris
 
Tim,

You have a few options here. If your code doesn't do anything too
tricky, you might be able to just add the /clr switch to the compiler
process and then you will automatically be able to access managed code.

Hope this helps.
 
Chris,
If I read between the lines here... I think you are saying I can't call a C#
managed DLL directly from C, I have to use a managed regular C++ DLL as a
wrapper, right?
 
C# dll's don't export functions the way C dll's do: they export classes
(which are not available to C).
So you can:
- Compile your C code in Managed C++ (the MC++ compiler understands about
anything the "old" C++ compiler did - I think they only switch the backend)
- Use a Managed C++ wrapper
- implement a COM interface in your C# class, and call that from C

Niki
 
Niki,
If I read between your lines.... I think you would recommened
in order of preference:

1. Compile with /clr
2. Managed C++ Wrapper
3. COM Interface

In that order, right ???

Thanks.
 
Back
Top