2016-04-03 16 views
1

假設我正在連接到C.如何傳遞extern(C)函數字面值?

這是接口的包裝功能。

@property extern(C) void onEvent(void function(InterfaceStruct*, int, int, int) nothrow callback) 
{ 
     interfaceSetCallback(handle, callback); 
} 

一切都好。

wrapper.onEvent = function void (InterfaceStruct*, int x, int y, int z) nothrow 
{ 
     if (x == 11) doSomething(); 
}; 

嗯哦:

Error: function foo.bar.onEvent (void function(InterfaceStruct*, int, int, int) nothrow callback) is not callable using argument types (void function(InterfaceStruct* _param_0, int x, int y, int z) nothrow @nogc @safe) 

所以,要我有函數文本是的extern(C)。那我該怎麼做?我找不到任何方法來這樣做。

回答

3

而是提供全功能的定義,你可以簡單地指定的onEvent使用

wrapper.onEvent = (a, x, y, z) 
{ 
    if (x == 11) doSomething(); 
}; 

d將自動爲其分配正確的類型。

此外,你的代碼實際上應該給你一個語法錯誤,因爲當使用它作爲函數指針定義時,實際上不允許使用extern(C)。

你可以交替定義的函數指針類型的別名和鑄鐵分配給它這樣的:

alias EventCallback = extern(C) void function(InterfaceStruct*, int, int, int) nothrow; 

@property extern(C) void onEvent(EventCallback callback) 
{ 
     interfaceSetCallback(handle, callback); 
} 

// ... 

wrapper.onEvent = cast(EventCallback) function void(InterfaceStruct*, int x, int y, int z) nothrow 
{ 
     if (x == 11) doSomething(); 
}; 
+0

嘿,謝謝!我無法在網上找到關於函數指針或文字的太多內容。另外,感謝您提供的第二個選項。我已經知道了那個(在查看其他代碼之後),但我並沒有儘可能地使用cast。幸運的是,現在,我不需要。 –