Search code examples
c++cvisual-studiodlllinkage

C linkage function cannot return c++ class when converting cpp to dll


After following some simple tutorial, I want to convert my cpp program to a dll file, however, it return several errors, like

C2526'split':c linkage function cannot return c++ class 'std::vector<std::string,std::allocator<std::string>>'

C2371'split':redefinition;different basic types
C2491 'split':definition of dllimport function not allowed
C2065 'split':undeclared identifier

in pch.h

#ifndef PCH_H
#define PCH_H

#include "framework.h"

#endif //PCH_H

#ifdef IMPORT_DLL
#else
#define IMPORT_DLL extern "C" _declspec(dllimport) //I follow tutor, but I doubt it cannot works if you use cpp when define extern "C"
#endif

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
IMPORT_DLL std::vector<std::string> split(std::string s, std::string delimiter);
IMPORT_DLL std::string removespaces(std::string str);
IMPORT_DLL std::string findevent(std::string str);

in pch.cpp

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>

std::vector<std::string> split(std::string s, std::string delimiter) 
{}
std::string removespaces(std::string str)
{}
std::string findevent(std::string str)
{}

I am sorry, I am a novice in cpp and dll,so any suggestion is helpful! Need I rewrite all program to c, not cpp?


Solution

  • About C calling C++ DLL, you need to pay attention to the following points:

    1.The C++ function interface for C calls cannot contain C++-specific things.

    2.When compiling a dll called by c code, extern "C" should be added before the function declaration in the header file to tell the compiler to process the function name according to the c specification.

    3.After the compilation is completed, the header file provided for c cannot contain extern "C", which can be solved by using the macro switch, or by rewriting a header file.