请告诉我调用函数时我做错了什么?:
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr CreateSemaphore(uint dwDesiredAccess, long lInitialCount, long lMaximumCount, string lpName);
IntPtr pDll = NativeMethods.LoadLibrary(@"kernel32.dll");
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "CreateSemaphoreA");
CreateSemaphore createSemaphore = (CreateSemaphore)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(CreateSemaphore));
IntPtr theResult = createSemaphore(0,2,2,"qwerty");
我也尝试使用 PInvoke 来做:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern HANDLE CreateSemaphore(uint dwDesiredAccess, long lInitialCount, long lMaximumCount, string lpName);
IntPtr result = winapi.CreateSemaphore(0,0,3,"qwerty");
错误是可以更改内存等,但是我运行 CreateMutex (public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner, string lpName)) ,一切都很好((((
升级版:
[UnmanagedFunctionPointer(CallingConvention.StdCall,CharSet = CharSet.Ansi)]
private delegate IntPtr CreateSemaphore(IntPtr dwDesiredAccess, long lInitialCount, long lMaximumCount, string lpName);
IntPtr pDll = NativeMethods.LoadLibrary(@"kernel32.dll");
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "CreateSemaphoreA");
CreateSemaphore createSemaphore = (CreateSemaphore)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(CreateSemaphore));
IntPtr theResult = createSemaphore(new IntPtr(),2,2,"qwerty");