Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

.net - How can I insert C code into C++/CLI code?

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

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?

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?

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...