How to export C++ function as a dll that throws exception?
Asked Answered
H

3

8

When I try to export the following function as a dll:

extern "C" __declspec(dllexport) void some_func()
{
  throw std::runtime_error("test throwing exception");
}

Visual C++ 2008 gives me the following warning:

1>.\SampleTrainer.cpp(11) : warning C4297: 'some_func' : function assumed not to throw an exception but does
1>        The function is extern "C" and /EHc was specified

I need to extern "C" because I use Qt QLibrary to load the dll and resolve the function name. Without extern "C" it can't find the some_func() function.

Hysterical answered 25/1, 2010 at 19:35 Comment(0)
H
4

If you are determined to do what the compiler is warning you about, why not just suppress the warning?

#pragma warning(disable: 4247)
Hemoglobin answered 25/1, 2010 at 19:44 Comment(3)
thanks for the advice. However, is there any other way around this? I actually just want to export a C++ function.Hysterical
Then don't use extern "C", instead then use a .def file to force the exported name to be the undecorated name (or whatever you want).Hemoglobin
alternatively, you can try and figure out how to get QT to load the C++ decorated name.Hemoglobin
L
6

As far as I know /EHs must be used in case you need a "C" function that can throw. See this: /EH (Exception Handling Model). You need to set this in your VisualStudio Project.

On the contrary /EHc tells the compiler to assume that extern C functions never throw a C++ exception. And your compiler complains you that your void some_func() do throw.

Ly answered 1/11, 2012 at 16:31 Comment(0)
H
4

If you are determined to do what the compiler is warning you about, why not just suppress the warning?

#pragma warning(disable: 4247)
Hemoglobin answered 25/1, 2010 at 19:44 Comment(3)
thanks for the advice. However, is there any other way around this? I actually just want to export a C++ function.Hysterical
Then don't use extern "C", instead then use a .def file to force the exported name to be the undecorated name (or whatever you want).Hemoglobin
alternatively, you can try and figure out how to get QT to load the C++ decorated name.Hemoglobin
S
0

I believe the better way is to export the class then:

//
// Interface
//

// @file Api.h

class Export
{
public:
  // May throw
  virtual void someFunc() = 0;

public:
  Export(Export&&) = delete;
  Export& operator=(Export&&) = delete;

protected:
  Export() = default;
  ~Export() = default;
};

// Never throws
DLL_API(Export&) getExport();


//
// Implementation
//

#define DLL_API_IMPL

#include "Api.h"

struct ExportImpl: Export
{
  void someFunc() override { /* do something */ }
};

static ExportImpl exportInstance;

DLL_API(Export&) getExport()
{
  return exportInstance;
}

Surveyor answered 14/9 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.