如何将C代码插入C ++ / CLI代码? [英] How can I insert C code into C++/CLI code?

查看:253
本文介绍了如何将C代码插入C ++ / CLI代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用C编写的文件,我想插入到我的.NET C ++ / CLI代码中。

I have some files written in C that I want to insert into my .NET C++/CLI code.

此C代码非常庞大,尚未由我,所以对我来说翻译所有代码将是一项艰巨的任务。
如何插入此代码并调用所需的函数而不会出现任何兼容性问题?

This C code is huge and has not been written by me, so it would be a hard task to me 'translating' all the code. How can I insert this code and call the functions I need without any compatibility problems?

我曾经认为,如果C ++ / CLI肯定是C ++并且C与C ++兼容,将C代码插入C ++ / CLI代码没有问题。但是我读过一些叫做 extern C 的东西,这让我改变了主意。

I used to think that, if C++/CLI is definitely C++ and C is compatible with C++, there is no problem to insert C code into C++/CLI code. But I've read about something called extern "C", which made me change my mind.

如何我将代码插入项目中,最好插入另一个文件中吗?

How can I insert the code into my project, preferably in another file?

预先感谢您。

推荐答案

C ++无需修改即可运行C代码。唯一的区别是函数和变量名称的编码方式。该过程称为名称处理

C++ can run C code without modifications. The only difference is the way the names of functions and variables are encoded. The process is called name mangling.

只需将您的C代码(标题和源代码)放在外部 C 块中:

Just enclose your C code (headers and source) in a extern "C" block:

extern "C" {
   ... (C code)
}

所有C代码必须在这样的块中编写。这告诉C ++编译器如何处理函数和变量名。阅读有关 extern C 这里

All C code must be written in such a block. This tells C++ compiler how to treat function and variable names. Read more about extern "C" here.

这篇关于如何将C代码插入C ++ / CLI代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆