using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;namespace LoadDll
{
/// <summary>
///
/// </summary>
class InvokeDll
{
#region Win API
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(string path); [DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, string funcName); [DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
#endregion private IntPtr hLib;
public InvokeDll(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
} ~InvokeDll()
{
FreeLibrary(hLib);
} //将要执行的函数转换为委托
public Delegate Invoke(string APIName, Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
if (api == IntPtr.Zero)
return null;
else
return Marshal.GetDelegateForFunctionPointer(api, t);
}
}}
如果c++导出函数中存在指针,一般怎么处理。用IntPtr行不行;采用Inptr处理返回值为指针的函数可以,为什么处理参数是指针的函数就不行了。还有没有别的处理方法忘高手指教。
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;namespace LoadDll
{
/// <summary>
///
/// </summary>
class InvokeDll
{
#region Win API
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(string path); [DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, string funcName); [DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
#endregion private IntPtr hLib;
public InvokeDll(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
} ~InvokeDll()
{
FreeLibrary(hLib);
} //将要执行的函数转换为委托
public Delegate Invoke(string APIName, Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
if (api == IntPtr.Zero)
return null;
else
return Marshal.GetDelegateForFunctionPointer(api, t);
}
}}
如果c++导出函数中存在指针,一般怎么处理。用IntPtr行不行;采用Inptr处理返回值为指针的函数可以,为什么处理参数是指针的函数就不行了。还有没有别的处理方法忘高手指教。
C#中定义为:
[DllImport("kernel32.dll")] //该库名视具体库名而定
private extern static void getArea(out double area);
楼主,你把不行的函数原型贴出来,同时把C#中的声明和使用也贴出来,因为每个环节都可能出错
extern "C" __declspec(dllexport) void point(char *p);char *pbuf = "abc";
void point(char *p)
{
p = pbuf;
}
c# 调用
public delegate void Point(out char chbuf);/*
Point point = (Point)invoke.Invoke("point", typeof(Point));
char buf;
point(out buf);
*/注释的这段应该怎么写??
c++ 导出函数
extern "C" __declspec(dllexport) void point(char *p);C#映射函数声明:
[DllImport("xx.dll",EntryPoint ="point",CharSet = CharSet.Ansi)]
public static extern void point(string p);2、“//将要执行的函数转换为委托 ”
你的需求中根本没有需要使用委托的地方,直接调用就可以了互操作需要进行委托处理的:是在C++这边使用了回调函数,即函数指针!
给你个例子:
C++:
void TestCallBack(FPTR pf, char* value);
bool FPtr(int value );C#:
public delegate bool FPtr2( string value );[ DllImport( "..\\LIB\\PinvokeLib.dll" )]
public static extern void TestCallBack( FPtr cb, string value );