Saturday, December 29, 2012

C#和VC++相互调用

All my technical notes will be written in English.
 It's possible to invoke VC++ DLL in C# by using System.Runtime.InteropServices.However,
it's tedious and error prone when the structs with pointer are
involved and things become even more complicated if some struct
contains other structs. You have to care about StructLayout and
Marshal.Actually, it may be more tedious than invoking DLL in
Java.

One grace
solution is to simplify the invoked method in VC++ side by
introducing managed code in VC++. It's better than introducing
unmanaged code in C# side. One simple example,

//
ManagedTest.cpp : main project file.


#include
"stdafx.h"

using
namespace System;

using
namespace System::Collections::Generic;


List<String^>^
MTest();


void main()
{


double number [] = { 79.31, 47.59, 749.75, 9.07, 9.44 };
Console::WriteLine(L"Value 1:  {0}", number[0]);

List<String^>^ list = MTest();
for(int i=0;i<list->Count;i++){
Console::WriteLine(list[i]);
}

Console::ReadLine();
}

List<String^>^
MTest(){

char tmp[] = "American College of Computer & Information Sciences";
String^ School = gcnew String(tmp);
String^ School2 = "American College of Computer & Information Sciences2";
List<String^>^ list = gcnew List<String^>();
list->Add(School);
list->Add(School2);
return list;
}



The problem for C# is that it has dependency on .NET framework and
a little lower than the native C++ program. Although ngen.exe could
be used to compiles an assembly to native code it still inevitable
to depend on .NET framework and ngen.exe only helps to reduce the
startup time.


When VC++ is using managed functions and aiming to try to export to the managed DLLs, it should be a CLR project as the great article "Walkthrough: Creating and Using a Managed Assembly (C++)" shows.
When C# side invokes the DLL, just add it to the reference and using the namespace to call the functions as if they are c# functions.
And the managed DLL cannot be displayed by dumpbin -exports
http://msdn.microsoft.com/zh-cn/library/ms235638(v=VS.100).aspx

No comments:

Post a Comment