C#을 이용해 프로그래밍을 하다보면 기존에 C, C++로 만들어둔 DLL을 사용해야 할 경우가 빈번하게 발생한다.
C#의 가장 강력한 기능중 하나는 C, C++ 라이브러리를 포괄적으로 지원해 준다는 점이다.
사용법은 다음과 같다.
C, C++ (Structure, Function)
#define JK_API __declspec(dllexport)
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _JK_test_struct{
int count;
char name[32];
}JK_test_struct;
JK_API int JK_test_function(JK_test_struct* jkStruct)
{
// ...
}
#ifdef __cplusplus
}
#endif
C# NativeMethods Class
namespace JK_space
{
internal struct JK_test_struct {
[MarshalAs(UnmanagedType.I4)]
public int count;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string name;
};
internal static class JKNativeMethods
{
[DllImport("FSB.dll")]
[return: MarshalAs(UnmanagedType.I4)]
internal static extern int JK_test_function(ref JK_test_struct jkStruct);
}
}
C# Main
namespace JK_space
{
public class JKTestClass
{
public static void Main(string[] args)
{
// member variables already memory allocated.
JK_test_struct jkStruct = new JK_test_struct();
JKNativeMethods.JK_test_function(ref jkStruct);
System.Console.WriteLine("count is " + jkStruct.count);
System.Console.WriteLine("name is " + jkStruct.name);
}
}
}
댓글 없음:
댓글 쓰기