作者cole945 (躂躂..)
看板C_Sharp
標題Re: [問題] Callback 函式 (C# 呼叫 C++ dll) (用 …
時間Wed Sep 16 23:17:41 2009
→ percyy:嗯...什麼意思? @@"
如果這程式有問題的話, 應該在runtime會有exception呀?
DllImport 不到進入點, 應該會有找不到進入點的exception,
calling converntion或參數大小不到, 應該會告訴你 stack 爛掉 的excetion
callback function pointer有誤, C/C++端呼叫時說不定會直接當掉..
或是 delegate 被GC回收了, 在debug環境下, 應該也會有exception
如果你什麼 exception都沒收到,
要不是被你自己catch起來和諧掉了, 就是C/C++那邊根本沒有呼叫該callback
推 cplusplus:基本上 unmanaged C++ 不能直接call C#的method...
這確定可以呼叫 @.@
舉個例子, 用 CreateThread() Windows API 來 create thraed,
而非使用 .NET 的 Thread Class
--
/*
* 這理是 p/invoke 相關的宣告
*/
delegate Int32 ThreadStartDelegate(IntPtr arg);
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(
IntPtr SecurityAttributes,
uint StackSize,
ThreadStartDelegate StartFunction,
IntPtr ThreadParameter, uint CreationFlags, out uint ThreadId);
/*
* 這裡是使用該 p/invoke 的 code
*/
// CreateThread 在 .NET 的 callback
Int32 MyThread(IntPtr arg)
{
Console.WriteLine("Hello World");
}
// 呼叫 CreateThread
int tid;
IntPtr h;
ThreadStartDelegate td = new ThreadStartDelegate(MyThread);
h = CreateThread(IntPtr.Zero, 0, td, IntPtr.Zero, 0, out tid);
// 這裡應該還要放個 WaitForSingleObject 等 Thread 結束....
GC.KeepAlive(td);
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.204.66.43
1F:→ percyy:無任何exception 我也沒處理 傾向於callback函式沒被執行到 09/16 23:32
2F:推 percyy:BTW, 我的平台是 Vista 64 Enterprise、Visual Studio 2008 09/16 23:35
3F:推 percyy:DLL的函式的回傳值也正常 但就是沒有callbak函式 09/16 23:41
4F:→ cole945:所以你的環境是64bit? 試試看在project設定中的Built-> 09/16 23:41
5F:→ cole945:platform target設成x86呢? 09/16 23:42
6F:推 percyy:我已經設了~ 有設才能 import 32-bit 的 DLL 09/17 00:44
7F:推 percyy:為什麼CreatThread第三個參數是丟null而不是td呢? 09/17 00:51
8F:→ percyy:(不好意思 我對 Windows API 不是很了解 ^^") 09/17 00:52
9F:→ cole945:因為我寫錯了...是丟td XD 09/17 01:03
※ 編輯: cole945 來自: 123.204.66.43 (09/17 01:03)
10F:→ cole945:感謝提醒, 我大E修正了~ 09/17 01:03
11F:推 percyy:所以照理說 透過delegate C/C++可以回呼C# 結果我的只肯 09/17 15:45
12F:→ percyy:吃long 變得不知該怎麼辦 問問券商能否提供裡面的資訊 09/17 15:45
13F:→ cole945:應該不會是long的問題@@ 因為delegate本來就會被marsah成 09/17 16:41
14F:→ cole945:function pointer, 而在.NET, pointer的size視平台而異, 09/17 16:41
15F:→ cole945:在x86-32, 其實也就是32bit, 與你在C/C++的long是一樣的.. 09/17 16:41
16F:→ cole945:若有問題的話,應該會有runtime錯誤. 若都沒出現, 應該比較 09/17 16:43
17F:→ cole945:像根本沒呼叫到吧@@" 09/17 16:43
18F:推 cplusplus:原來直接傳delegate? @@ 我找不到把delegate轉成long的 09/29 14:25
19F:→ cplusplus:方法 @@ 所以原PO的方式不能搞 不過的確可以回乎m(_ _)m 09/29 14:27
20F:推 percyy:所以說 就算 delegate 轉成 IntPtr 也不能相容於 long 嗎? 10/01 08:52
21F:推 cplusplus:樓上,我本來以為delegate會內含一個IntPtr的member 10/03 01:41
22F:→ cplusplus:結果找了一找,沒有...@@ 不像winform裡面有handle... 10/03 01:42
23F:→ cplusplus:然後也找不到轉換的方法 所以我當初覺得沒有 10/03 01:42