我正在制作一套框架。我想支持多种编程语言

时间:2011-09-27 22:12:18

标签: frameworks programming-languages libraries

我正在制作一套框架。

我想支持多种编程语言。

我的问题是我应该用什么语言作为基础?

有没有办法进行多重绑定?

我想支持所有这些编程语言。

C, C++, Java, Ruby, Perl, Python.

3 个答案:

答案 0 :(得分:1)

查看GObject - 它是一个开源C库,为C添加面向对象的编程功能,并且可以透明地为a variety of languages创建绑定。

它的同伴Vala是一种面向对象的语言,可以编译成C + GObject代码,以帮助减少C + GObject的冗长。

答案 1 :(得分:1)

查看SWIG," Simplified Wrapper和Interface Generator"。给定C或C ++代码,它可以以编程方式为a variety of languages生成绑定。

答案 2 :(得分:1)

我会用C ++实现库。如果你需要C访问权限,那么通过提供带有额外“this”参数的包装函数,可以很容易地手动完成。

在开始之前,请阅读SWIG文档,特别是其限制和要避免的事项。如果您考虑使用SWIG设计C ++接口,您可以轻松获得为您生成的大量语言的绑定。

编辑:这是一个C ++类的C包装器的快速示例。假设这是要包装的C ++类,我们称之为test.h

class Test {
public:
    Test();
    int do_something(char* arg);
private:
    is_valid(); // see below for why you need this method
};

这是您的C标头test_c.h

typedef void* TestHandle;
TestHandle newTest();
int deleteTest(TestHandle h);
int Test_do_something(TestHandle h, char* arg);

你的C实现将是一个带有C函数的C ++文件,比方说test_c.cpp

extern "C" TestHandle newTest()
{
    return (void*)new Test();
}

extern "C" int deleteTest(TestHandle h)
{
    Test* this = static_cast<Test*>(h);
    if (!this->is_valid())
        return -1; // here we define -1 as "invalid handle" error
    delete this;
    return 0; // here we define 0 as the "ok" error code
}

extern "C" int Test_do_something(TestHandle h, char* arg)
{
    Test* this = static_cast<Test*>(h);
    if (!this->is_valid())
        return -1; // here we define -1 as "invalid handle" error
    return this->do_something(arg);
}   

is_valid()方法可以保证您不会传递错误句柄。例如,您可以在所有实例中存储magic number,然后is_valid()只确保幻数存在。

相关问题