DLLの動的リンク



アンマネージDLLを動的にリンクする(と、コールバックの実装)

OldDll.cpp
#include "windows.h"

#ifdef EXPORT
  #define DLLEXPORT __declspec(dllimport)
#else
  #define DLLEXPORT __declspec(dllexport)
#endif

#ifdef _MANAGED
  #pragma managed(push, off)
#endif

#ifdef __cplusplus
  extern "C" {
#endif

typedef int (__stdcall *CallBackFuncPtr)( int );
static CallBackFuncPtr CallBackFunc;	
	
DLLEXPORT void SetFunc(CallBackFuncPtr ptr) {
    CallBackFunc = ptr;
}
DLLEXPORT int CallFunc(int i) {
    return CallBackFunc(i);
}
DLLEXPORT int TestFunc( int i) {
    return i;
}
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved ) {
    return TRUE;
}

#ifdef __cplusplus
  }
#endif

#ifdef _MANAGED
  #pragma managed(pop)
#endif
Test.cs
using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices ;  // for DllImport

namespace Test {
    class Program {
        public delegate int CallbackProc(int i);

        [DllImport(@"..\..\..\debug\OldDll.dll")]
        public static extern int TestFunc(int i);

        [DllImport(@"..\..\..\debug\OldDll.dll")]
        public static extern int CallFunc(int i);

        [DllImport(@"..\..\..\debug\OldDll.dll")]
        public static extern void SetFunc(CallbackProc proc);

        static void Main(string[] args) {
            SetFunc(delegate (int i) {
                return i*2;
            });

            Console.WriteLine("TestFunc(2) = " + TestFunc(2));
            Console.WriteLine("CallFunc(2) = " + CallFunc(2));
            Console.ReadLine();		
        }
    }
}
最終更新:2008年10月06日 21:53