Take the 2-minute tour ×

C# main program needs to call a C program GA.c This C code executes many functions and one function initialize() calls objective() function. But this objective function needs to be written in C#.This call is in a loop in the C code and the C code needs to continue execution after the return from objective() until its main is over and return control to C# main program.

C# main()

  call to GA in C;
  //remaining code;

GA in C:

Ga Main()

 call to initialize function();
 //remaining code

initialize function() in GA

 for(some condition)
   call to objective(parameter) function in C#;

How do we do this?

share|improve this question
Do you call GA_main directly from C#? or do you use a Process object to run Ga.exe? (is GA a program or a dll?) –  John Knoeller Mar 24 '10 at 3:57
@John Knoeller ... We call GA_main directly from C# –  Prithvi Mar 24 '10 at 4:39
and this call to GA_main is already working? or do you need to know how to do that also? –  John Knoeller Mar 24 '10 at 23:05
add comment

3 Answers

Your unmanaged C code needs to be in a library, not an executable. When a program "calls another program", that means it executes another executable, and any communication between the two processes is either in the form of command-line arguments to the callee coupled with an integer return value to the caller, or via some sort of IPC*. Neither of which allows the passing of a callback function (although equivalent functionality can be built with IPC, it's a lot of trouble).

From this C library, you'll need to export the function(s) you wish to be entry points from the C# code. You can then call this/these exported function(s) with platform invoke in C#.

C library (example for MSVC):

#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){
    return TRUE;

#ifdef __cplusplus
extern "C"
void WINAPI Foo(int start, int end, void (CALLBACK *callback)(int i)){

C# program:

using System;
using System.Runtime.InteropServices;

static class Program{

    delegate void FooCallback(int i);

    static extern void Foo(int start, int end, FooCallback callback);

    static void Main(){
        FooCallback callback = i=>Console.WriteLine(i);
        Foo(0, 10, callback);
        GC.KeepAlive(callback); // to keep the GC from collecting the delegate

This is working example code. Expand it to your needs.

A note about P/Invoke

Not that you asked, but there are two typical cases where platform invoke is used:

  1. To leverage "legacy" code. A couple of good uses here:

    • To make use of existing code from your own code base. For instance, your company might want a brand new GUI for their accounting software, but choose to P/Invoke to the old business layer so as to avoid the time and expense of rewriting and testing a new implementation.

    • To interface with third-party C code. For instance, a lot of .NET applications use P/Invoke to access native Windows API functionality not exposed through the BCL.

  2. To optimize performance-critical sections of code. Finding a bottleneck in a certain routine, a developer might decide to drop down to native code for this routine in an attempt to get more speed.

It is in this second case that there is usually a misjudgment. A number of considerations usually prove this to be a bad idea:

  1. There is rarely a significant speed benefit to be obtained by using unmanaged code. This is a hard one for a lot of developers to swallow, but well-written managed code usually (though not always) performs nearly as fast as well-written unmanaged code. In a few cases, it can perform faster. There are some good discussions on this topic here on SO and elsewhere on the Net, if you're interested in searching for them.

  2. Some of the techniques that can make unmanaged code more performant can also be done in C#. Primarily, I'm referring here to unsafe code blocks in C#, which allow one to use pointers, bypassing array boundary checking. In addition, straight C code is usually written in a procedural fashion, eliminating the slight overhead that comes from object-oriented code. C# can also be written procedurally, using static methods and static fields. While unsafe code and gratuitous use of static members are generally best avoided, I'd say that they are preferable to mixing managed and unmanaged code.

  3. Managed code is garbaged-collected, while unmanaged code is usually not. While this is mostly a speed benefit while coding, it is sometimes a speed benefit at runtime, too. When one has to manage one's own memory, there is often a bit of overhead involved, such as passing an additional parameter to functions denoting the size of a block of memory. There is also eager destruction and deallocation, a necessity in most unmanaged code, whereas managed code can offload these tasks to the lazy collector, where they can be performed later, perhaps when the CPU isn't so busy doing real work. From what I've read, garbage collection also means that allocations can be faster than in unmanaged code. Lastly, some amount of manual memory management is possible in C#, using Managed.AllocHGlobal and unsafe pointers, and this might allow one to make fewer larger allocations instead of many smaller ones. Another technique is to convert types used in large arrays to value types instead of reference types, so that the memory for the entire array is allocated in one block.

  4. Often overlooked is the cost within the platform invoke layer. This can outweigh small native code performance gains, especially when many transitions from managed to unmanaged (or vice versa, such as with your callback function) must occur. And this cost can increase exponentially when marshaling must take place.

  5. There's a maintenance hassle when splitting your code between managed and unmanaged components. It means maintaining logic in two different projects, possibly using two different development environments, and possibly even requiring two different developers with different skill sets. The typical C# developer is not a good C developer, and vice versa. At minimum, having the code split this way will be a mental stumbling block for any new maintainers of the project.

  6. Oftentimes, a better performance gain can be had by just rethinking the existing implementation, and rewriting it with a new approach. In fact, I'd say that most real performance gains that are achieved when bottleneck code is rewritten for a "faster" platform are probably directly due to the developer being forced to rethink the problem.

  7. Sometimes, the code that is chosen to be dropped out into unmanaged is not the real bottleneck. People too often make assumptions about what is slowing them down without doing actual profiling to verify. Profiling can often reveal inefficiencies that can be correctly fairly easily without dropping down to a lower-level platform.

If you find yourself faced with a temptation to mix platforms to increase performance, keep these pitfalls in mind.

* There is one more thing, sort of. The parent process can redirect the stdin and stdout streams of the child process, implementing character-based message passing via stdio. This is really just an IPC mechanism, it's just one that's been around longer than the term "IPC" (AFAIK).

share|improve this answer
add comment

This is known as a callback. When you create an instance of GA, pass it your c# objective() method as a delegate (a delegate is reference to a class method). Look for the MSDN help topic on delegates in C#.

I don't know the proper syntax for the C side of this. And there are sure to be some special considerations for calling out to unmanaged code. Someone else is bound to provide the whole answer. :)

share|improve this answer
add comment

You might want to check this posting out: http://www.codeproject.com/KB/mcpp/unmanaged_to_managed.aspx

share|improve this answer
add comment

Your Answer


