C#调用cdll指针参数处理

1、API声明(包括**参数)

int GetTheLastErrorA(char **pcError);
int GetTheLastErrorW(wchar_t **pwError);

2、C#代码

using System.Runtime.InteropServices;

[DllImport("StringAW.dll", CallingConvention = CallingConvention.Winapi, 
CharSet = CharSet.Ansi, EntryPoint = "GetTheLastErrorA")]
extern static int GetTheLastErrorA(ref IntPtr a);

[DllImport("StringAW.dll", CallingConvention = CallingConvention.Winapi, 
CharSet = CharSet.Auto, EntryPoint = "GetTheLastErrorW")]
extern static int GetTheLastErrorW(ref IntPtr w);

IntPtr a = IntPtr.Zero;
GetTheLastErrorA(ref a);
String sa = Marshal.PtrToStringAnsi(a);
MessageBox.Show(sa);

IntPtr w = IntPtr.Zero;
GetTheLastErrorW(ref w);
String sw = Marshal.PtrToStringUni(w);
MessageBox.Show(sw);

Python调用dll

1.Test.h

#ifndef TEST_INTADD_HEADER
#define TEST_INTADD_HEADER

extern "C" int WINAPIV IntAdd(int a,int b);

#endif

2.Test.cpp

#include <windows.h>
#include "Test.h"

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved)
{
  UNREFERENCED_PARAMETER(hinstDLL);
  UNREFERENCED_PARAMETER(lpReserved);

  switch(fdwReason) 
  { 
    case DLL_PROCESS_ATTACH:
      break;

    case DLL_THREAD_ATTACH:
      break;

    case DLL_THREAD_DETACH:
      break;

    case DLL_PROCESS_DETACH:
      break;
  }

  return TRUE;
}

extern "C" int WINAPIV IntAdd(int a,int b)
{
  return a+b;
}

3.Test.def

LIBRARY	"Test"

EXPORTS
	IntAdd

4.test_cdll.py

#test_cdll.py
#请用__cdecl调用约定而不是__stdcall

from ctypes import *

fileName="Test.dll"
Test=cdll.LoadLibrary(fileName)
print(Test.IntAdd(2,3))