본문 바로가기

프로그래밍/C#

C++ PInvoke를 사용하여 함수 포인터 마샬링

반응형

 

// TraditionalDll5.cpp

// compile with: /LD /EHsc

#include <iostream>

#define TRADITIONALDLL_EXPORTS

#ifdef TRADITIONALDLL_EXPORTS

#define TRADITIONALDLL_API __declspec(dllexport)

#else

#define TRADITIONALDLL_API __declspec(dllimport)

#endif

 

extern "C" {

   /* Declare an unmanaged function type that takes two int arguments

      Note the use of __stdcall for compatibility with managed code */

   typedef int (__stdcall *CALLBACK)(int);

   TRADITIONALDLL_API int TakesCallback(CALLBACK fp, int);

}

 

int TakesCallback(CALLBACK fp, int n) {

   printf_s("[unmanaged] got callback address, calling it...\n");

   return fp(n);

}

 

 

 

 

// MarshalDelegate.cpp

// compile with: /clr

using namespace System;

using namespace System::Runtime::InteropServices;

 

public delegate int GetTheAnswerDelegate(int);

public value struct TraditionalDLL {

   [DllImport("TraditionalDLL5.dll")]

   static public int TakesCallback(GetTheAnswerDelegate^ pfn, int n);

};

 

int GetNumber(int n) {

   Console::WriteLine("[managed] callback!");

   static int x = 0;

   ++x;

   return x + n;

}

 

int main() {

   GetTheAnswerDelegate^ fp = gcnew GetTheAnswerDelegate(GetNumber);

   pin_ptr<GetTheAnswerDelegate^> pp = &fp;

   Console::WriteLine("[managed] sending delegate as callback...");

 

   int answer = TraditionalDLL::TakesCallback(fp, 42);

 

 

 

반응형