经过与会代表在D外部C函数 [英] Pass delegates to external C functions in D
问题描述
我如何通过一个委托以函数指针,D中的外部C函数?
How do I pass a delegate to an external C function taking a function pointer, in D?
推荐答案
让我交交我说的新闻组:
Let me cross post what I said on the newsgroup:
我如何通过一个委托给外部C函数取
函数指针?
How do I pass a delegate to an external C function taking a function pointer?
您不能直接一般做到这一点,除非你能修改C
功能,那么你就可以破解它周围,而是一个委托和
普通函数指针是pretty不同的动物。
You can't do it directly in general, unless you can modify the C function, then you can hack around it, but a delegate and a regular function pointer are pretty different animals.
但是,也许你可以神奇的本事。注意:
But perhaps you can magic hack it. Observe:
// a C function that needs a plain function
extern(C) void test(void function() f) {
// pretend this is implemented in C
f();
}
// just create a random delegate
void delegate() foo(int a) {
return { import std.stdio; writeln(a); };
}
// what we want to work
void main() {
auto dg = foo(10);
dg(); // works
//test(dg); // won't work
test(bindDelegate(dg)); // we want this
}
// transform delegate into pointer..
import std.traits;
auto bindDelegate(T, string file = __FILE__, size_t line = __LINE__)(T t) if(isDelegate!T) {
static T dg;
dg = t;
extern(C)
static ReturnType!T func(ParameterTypeTuple!T args) {
return dg(args);
}
return &func;
}
什么bindDelegate所做的是创建一个特殊的静态变量和
功能为特定的呼叫。这是因为如果我们写了一个单独的
函数和全局持有它。
What bindDelegate does is create a special static variable and function for that specific call. It is as if we wrote a separate function and global to hold it.
的 __ __ FILE
, __ __ LINE
东西是一个肮脏的黑客攻击,使其
实例化一个独立的变量+功能,对不同的
线,使全局变量控股委托不会那么
轻易改写。
The __FILE__
, __LINE__
things are a filthy hack to make it
instantiate a separate variable+function pair for different
lines so the global variable holding the delegate won't be so
easily overwritten.
这篇关于经过与会代表在D外部C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!