type
TTestRecord = record
aInt: Integer;
aDouble: Double;
end;
PTestRecord = ^TTestRecord;
function RecordTest(var pBuf: PTestRecord): Integer;
想呼叫包含以上函式的DLL
我的做法
protected void Button6_Click(object sender, EventArgs e)
{
//1. 動態加載C++ Dll
int hModule = NativeMethod.LoadLibrary(@"c:\API.dll");
//2. 讀取函式指標
IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "RecordTest");
user_group_list structList = (user_group_list)Marshal.PtrToStructure(intPtr, typeof(user_group_list));
List<user_group_t> listGroupTemp = MarshalPtrToStructArray<user_group_t>(structList.group_array, structList.group_array_count);
StringBuilder sb = new StringBuilder();
foreach (user_group_t u in listGroupTemp)
{
sb.Append(u.aInt + "|" + u.aDouble + "<br/>");
}
Literal1.Text = sb.ToString();
}
public static List<T> MarshalPtrToStructArray<T>(IntPtr p, int count)
{
List<T> l = new List<T>();
for (int i = 0; i < count; i++, p = new IntPtr(p.ToInt32() + i*Marshal.SizeOf(typeof(T))))
{
T t = (T)Marshal.PtrToStructure(p, typeof(T));
l.Add(t);
}
return l;
}
public struct user_group_t
{
//public int id;
//public string name;
public int aInt;
public double aDouble; // balance
}
public struct user_group_list
{
public int group_array_count;
public IntPtr group_array;//指向 user_group_t型別的指標
}
程式走到這里 T t = (T)Marshal.PtrToStructure(p, typeof(T));
提示嘗試讀取或寫入受保護的記憶體。這通常指示其他記憶體已損壞。
然后就卡在這里不知道怎么走了
請問哪位大神知道的幫忙處理下或有什么新方法
uj5u.com熱心網友回復:
不用標記unsafe么
uj5u.com熱心網友回復:
回傳Json多好uj5u.com熱心網友回復:
IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "RecordTest");intPtr是函式指標,指向Dll中的一段代碼,而不是一段結構變數,你想用PtrToStructure把這段代碼封裝成什么物件?
用Delphi寫個Com組件來呼叫和訪問結構體,然后在C#中呼叫COM組件。
C#與非托管代碼的互動有多種手段,但通過COM是最可靠的。
uj5u.com熱心網友回復:
試試下面的方法:
using System.Runtime.InteropServices;
...
struct TTestRecord
{
int aInt;
double aDouble;
}
[DllImport(API.dll", EntryPoint="RecordTest")]
static extern unsafe int RecordTest(TTestRecord ** pBuf);
...
//呼叫處:
TTestRecord data;
unsafe
{
TTestRecord * ptr = & data;
RecordTest( & ptr );
}
uj5u.com熱心網友回復:
最好給結構加個packed,強迫位元組對齊,省的異構間的對齊問題轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/130907.html
標籤:語言基礎/算法/系統設計
上一篇:求助:Delphi下呼叫NIDAQmx的nicaiu.dll中的DAQmxCreateAIVoltageChan回傳-200088錯誤
