简体   繁体   English

从C ++调用C方法

[英]Calling a C method from C++

I know there are many SO questions related to this, but none of the ones I've come across solve my problem. 我知道有很多与此相关的问题,但是我遇到的所有问题都无法解决我的问题。 So here goes. 所以去。

I have a C++ file and method: 我有一个C++文件和方法:

MyClass.cpp MyClass.cpp

extern "C" {
#include "C_methods.h"
}

void MyClass::run_c_method_1()
{
    std::string filename_1 = <from somewhere else>;
    std::string filename_2 = <from somewhere else>;
    c_method_1(filename_1.c_str(), filename_2.c_str());
}

C_methods.h C_methods.h

#ifndef Project_C_methods_h
#define Project_C_methods_h

int c_method_1(char* filename1, char* filename_2);

#endif

C_methods.c C_methods.c

#include "C_methods.h"

int c_method_1(char* filename1, char* filename_2) {
  /* Do some stuff */
  return 0;
}

I'm building/running this on OSX in Xcode , and the compiler is telling me: 我正在Xcode OSX上构建/运行此文件,编译器告诉我:

No matching function call to 'c_method_1' . No matching function call to 'c_method_1'

To me, this makes no sense. 对我来说,这没有任何意义。 From other SO answers, it looks like the extern I've wrapped the header #include "C_methods.h" in should tell the compiler that those functions are present, and to be compiled in C . 从其他SO答案来看,看起来我已经将标头#include "C_methods.h"包裹在extern应该告诉编译器这些函数存在,并在C进行编译。

Does anyone have any idea where I could be going wrong here? 有谁知道我在这里哪里出错了? I'm stumped. 我很沮丧

Your problem can actually be simplified to this: 您的问题实际上可以简化为:

#include <string>

void foo(char *);

int main() {
    std::string s;
    foo(s.c_str());
}

The function takes a char * , but a const char * is passed to it. 该函数采用char * ,但是将const char *传递给它。 If the function does not modify the pointee, it should take a const char * . 如果该函数未修改pointee,则应采用const char * Otherwise, you'll have to use a modifiable buffer. 否则,您将不得不使用可修改的缓冲区。 As of C++11, std::string 's &s[0] counts as one up until just before the internal null character at the end. 从C ++ 11开始, std::string&s[0]计为一个,直到最后一个内部空字符之前。 Before that, you're better off with std::vector<char> . 在此之前,最好使用std::vector<char>

If a legacy function takes a non-const pointer but you know it WON'T modify the data (common in old C code), then it's permissible to use, in this case, const_cast<char *>(s.c_str()) . 如果旧版函数采用非const指针,但是您知道它不会修改数据(在旧的C代码中很常见),则可以使用const_cast<char *>(s.c_str()) If the function does modify the data, it's undefined behavior! 如果函数确实修改了数据,则为未定义行为!

If the function might modify the data then you need to copy your string into a modifiable buffer and pass a pointer to that instead. 如果该函数可能会修改数据,则需要将字符串复制到可修改的缓冲区中,然后将指针传递给该缓冲区。

string s;
vector<char> buffer(s.size() + 1); // prepare buffer, with space for null char
strcpy(buffer.data(), s.c_str()); // copy string data
foo(buffer.data());
s = buffer.data(); // copy back string data if required

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

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