英文:
How can I take my C code and use it on the web?
问题
我正在制作一个黑白棋游戏,我已经用C编写了我的机器人算法。但是,我想创建一个基于Web的GUI,并且希望通过Web应用程序调用我用C编写的算法(我不想使用JavaScript重新编写我的机器人)。
我在网上搜索了一下,我认为这个问题与API有关,但我真的不知道该怎么做或从哪里开始。有任何帮助吗?
英文:
I'm making a Reversi game and I coded my bot algorithm in C. However, I want to create a web based GUI and somehow be able to call my algorithm written in C through the web app (I don't want to recode my bot using javascript).
I've searched around online and I think that this problem has to do something related to APIs, but I don't really know what to do or where to start. Any help?
答案1
得分: 1
假设您已经为Web应用程序拥有后端,您可以将C代码编译成DLL(在Windows上)或SO(在基于Unix的系统上)文件,然后在后端代码中调用它。
例如,创建SO文件:
gcc -c -fPIC myfile.c -o myfile.o
gcc -shared myfile.o -o libmyfile.so
我们将代码编译成一个目标文件,并将其链接到一个SO文件。-fPIC标志指定了位置无关的代码,这对于创建共享对象是必需的。
请注意,共享对象的命名约定通常是以"lib"为前缀,并使用扩展名.so。
一旦您拥有DLL或SO文件,您可以在后端服务器代码中加载它,并调用C算法中定义的函数。加载库的确切方法将取决于您选择用于后端的编程语言和框架。
举个在Node.js服务器中的示例:
- 首先安装ffi包:
npm install ffi
- 在代码中做类似以下的操作:
const ffi = require('ffi');
// 加载共享对象文件
const myLibrary = ffi.Library('/path/to/myLibrary.so', {
'myFunction': ['int', ['int', 'int']]
});
const result = myLibrary.myFunction(3, 4);
console.log(result);
在这个示例中,myFunction是共享对象文件myLibrary.so中定义的函数。该函数接受两个整数参数并返回一个整数结果。您可以根据您的特定共享对象文件调整函数签名和数据类型。希望这有所帮助。
英文:
Assuming that you already have an back-end for the webapp, you can compile the C code into a DLL (in windows) or an SO (in Unix based systems) file and then call it in the backend code.
For example creating an SO file
gcc -c -fPIC myfile.c -o myfile.o
gcc -shared myfile.o -o libmyfile.so
We are compiling the code into an object file and linking it to an SO file. The -fPIC flag specifies position-independent code, which is required for creating shared objects.
> Note that the name convention for shared objects is often to prefix
> them with "lib" and use the extension .so.
Once you have the DLL or SO file, you can load it within your backend server code and call the functions defined in your C algorithm. The exact method for loading the library will depend on the programming language and framework you choose for your backend.
To give an example in Node JS server,
- First install the ffi package
npm install ffi
- In the code do something like
const ffi = require('ffi');
// Load the shared object file
const myLibrary = ffi.Library('/path/to/myLibrary.so', {
'myFunction': ['int', ['int', 'int']]
});
const result = myLibrary.myFunction(3, 4);
console.log(result);
In this example, myFunction is the function defined in the shared object file myLibrary.so. The function takes two integer arguments and returns an integer result. You can adjust the function signature and data types according to your specific shared object file.
hope it helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论