简体   繁体   English

从C ++ / Java / C#代码调用C方法?

[英]Call C methods from C++/Java/C# code?

Many of today's programming languages are based on C; 今天的许多编程语言都基于C; like C++, C#, Java, Objective-C. 比如C ++,C#,Java,Objective-C。 So could I call a C method from C++ code? 那我可以用C ++代码调用C方法吗? Or call C from Java or C#? 或者从Java或C#调用C? Or is this goal out of reach and unreasonable? 或者这个目标是否达不到和不合理? Please include a quick code sample for my and everyone else's understanding. 请为我和其他人的理解提供快速代码示例。

C++,C#, Objective-C, and Java can all call C routines. C ++,C#,Objective-C和Java都可以调用C例程。 Here are a few links that will give you an overview of the process needed to call C from each language you asked about. 以下是一些链接,它们将概述从您询问的每种语言调用C所需的过程。

An example of calling C from C++. 从C ++调用C的示例。 Save this C function in a file called ac: 将此C函数保存在名为ac的文件中:

int f() {
   return 42;
}

and compile it: 并编译它:

gcc -c a.c

which will produce a file called ao Now write a C++ program in a file called main.cpp: 这将生成一个名为ao的文件现在在名为main.cpp的文件中编写一个C ++程序:

#include <iostream>
extern "C" int f();

int main() {
   std::cout << f() << std::endl;
}

and compile and link with: 并编译和链接:

g++ main.cpp a.o -o myprog

which will produce an execuatable called myprog which prints 42 when run. 这将生成一个可执行的名为myprog的命令,在运行时打印42。

To Call C Methods In Java... 在Java中调用C方法...

there a Keyword "native" in Which You can write machine-dependent C code and invoke it from Java.... 有一个关键字“本机”,你可以编写机器相关的C代码并从Java调用它....

Basically it creates a DLL file..then u have to load it in ur program... 基本上它创建了一个DLL文件..然后你必须在你的程序中加载它...

a nice example here .... 这里一个很好的例子....

To call C methods from Java, there are multiple options, including: 要从Java调用C方法,有多个选项,包括:

  • JNA - Java Native Access. JNA - Java Native Access。 Free. 自由。 Easy to use. 使用方便。 Hand-declaration of Java classes and interfaces paralleling existing C structs and functions. 手工声明Java类和接口,与现有的C结构和函数并行。 Slower than JNI - by a few hundred nanoseconds per call. 比JNI慢 - 每次通话几百纳秒。
  • JNI - Java Native Interface. JNI - Java Native Interface。 Free. 自由。 Fastest option. 最快的选择。 Requires a layer of native glue code between your Java code and the native functions you want to call. 在Java代码和要调用的本机函数之间需要一层本机粘合代码。
  • JNIWrapper - Commercial product, similar to JNA. JNIWrapper - 商业产品,类似于JNA。

要从Java调用C / C ++,还要看看BridJ (它就像JNA与C ++和更好的性能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM