Accessing C++ templates from C - c++

I am using OpenCV for some image manipulation and it has several functions that must be given a data type to perform correctly. My idea is to template these functions so I do not have to write a separate function for each possible data type it could be.
However, the code I would like the code I am writing to be compatible with some existing C code I have that stores images in memory so I can pass it around easier without writing the image to disc constantly.
The problem I am running into is how to make my .h files and libraries to let the C program call the C++ template functions. I have not had a chance to try it yet, but so far what I have would look something what follows:
foo.h
int foo(int a, int, b);
float foo(float a, float b);
foo.c:
int foo(int a, int b) {
return footemp(a, b);
}
float foo(float a, float b) {
return footemp(a, b);
}
foo.hpp:
template<class t>
t footemp(t a, t b) {
return a + b;
}
Which does not work since it requires my .c file to know about a templated file.
So I am open to suggestions. Thank you in advance for the help

This is possible, with some care. Use a C++ source file foo.cpp:
#include "foo.h"
#include "footemp.hpp"
int foo_int(int a, int b) {
return footemp(a, b);
}
float foo_float(float a, float b) {
return footemp(a, b);
}
In foo.h, use extern "C" to make C-compatible declarations, with an #ifdef to allow use as either C or C++:
#ifdef __cplusplus
extern "C" {
#endif
int foo_int(int a, int, b);
float foo_float(float a, float b);
#ifdef __cplusplus
}
#endif
Compile this as a C++ library—static or dynamic, it doesn’t matter. In your C sources you can now #include "foo.h" and use these functions as you would expect, so long as you link against the library.

I imagine one thing you could do is write the function in C++, declaring the specializations you want, and at the same time defining extern "C" functions that forward the calls to the template functions.
Keep in mind if you're using C for the other stuff, you're going to need to name the functions different; C doesn't do function overloading.

As mday299 mentioned, there is no templates in C.
However, if your C code is contained in a saparate compilation unit (.exe/.dll), you can provide C interface for your template functions almost like you did it:
foo.h
/* C interface */
int fooInt(int a, int, b);
float fooFloat(float a, float b);
foo.hpp
template <class T> foo(T a,T b)
{
return a+b;
}
foo.cpp:
#include "foo.h"
#include "foo.hpp"
int fooInt(int a, int b) {
return foo<int>(a, b);
}
float fooFloat(float a, float b) {
return foo<float>(a, b);
}
Then, project would be compiled separate using c++, and c part would see only foo.h and lib/dll file

No templates in C. That's a C++ feature. Sorry.

There is a good chance that you'll be able to compile your C file with a C++ compiler. So you can build your whole project, both C and C++ sources with a C++ compiler.
You are already compiling it with a C++ compiler, otherwise you wouldn't be able to compile your overloaded foo functions.

Related

Where should I include <complex>

I've got a couple of header/source files: FUNCS.h and FUNCS.cpp, MATRIX.h and MATRIX.cpp, and main.cpp
. In funcs and my MATRIX class there should be complex library, but when I try to include it in my MATRIX.h for example, I get error that complex is not a template.
Where should I include the library so all my headers would define complex as a template?
Example:
#pragma once
#include <complex>
class MATRIX
{
friend MATRIX sum(MATRIX a, MATRIX b);
friend MATRIX mult(MATRIX a, MATRIX b);
friend MATRIX vi4(MATRIX a, MATRIX b);
friend MATRIX operator * (const MATRIX& a, complex<int> b);
friend MATRIX operator * (complex<int> b, const MATRIX& a);
private:
complex<int>** M;
int m;
int n;
public:
MATRIX();
MATRIX(int _m, int _n);
MATRIX(int _m);
MATRIX(const MATRIX& _M);
complex<int> get(int i, int j);
void set(int i, int j, complex<int> value);
void Print();
MATRIX operator=(const MATRIX& _M);
complex<int>* operator[] (int index);
~MATRIX();
};
What is defined in <complex> is std::complex, what you are trying to use is complex, and the compiler cannot find something called complex in the global scope.
Change
friend MATRIX operator * (complex<int> b, const MATRIX& a);
to
friend MATRIX operator * (std::complex<int> b, const MATRIX& a);
Or introduce the name via
using std::complex;
but don't do that in a header! Rather put that in the source file only. The reason to not do it in a header is that all other code that includes the header will "inherit" it and it will lead to problems on the long run.
The header you should include in every file that uses std::complex.
Note that sometimes you can get away with including it indirectly, as in: a.h includes <complex>, b.h includes a.h hence it can use std::complex without expliticly including <complex>. Do not rely on that! It will cause trouble on the long run.
Further note that often a forward declaration is sufficient. It goes beyond what you have in your example, but I mention it for the sake of completeness. You don't need the definition in a header when all you use is pointers and references to a type. A declaration is sufficent in this case and the header can be included in the source only. This can reduce compilation time in huge projects.
Where should I include <complex>
In every file where you use the declarations of that file, before those usages. Conventionally, headers are included at the beginning (head) of the file
complex<int>** M;
I get error that complex is not a template.
<complex> doesn't declare ::complex. It declares std::complex. Use std::complex instead.

Wrapper function for template<> in C++

I am currently trying to create a wrapper interface that can translate C++ to C, and while studying on the possibilities to do that, I came across the template functions (and classes). Knowing that these functions can take any data type and return any data type as well, I find it hard to create a corresponding caller function name that C could read. A simple example is the adder.
template <class typesToAdd>
typesToAdd addStuff(typesToAdd a, typesToAdd b) {
return a + b;
}
My interface includes the extern "C" command to avoid the C++ name mangling in C.
Template is not a function that works for any data type. It is a template for a function that is created at compilation time. Each type you use creates a new function with a new symbol in the binary.
To export to C, you will have to specialize the type you want to use from C, like:
template <class typesToAdd>
typesToAdd addStuff(typesToAdd a, typesToAdd b) {
return a + b;
}
extern "C" {
int addStuffInt(int a, int b) {
return addStuff(a, b);
}
}
You may use function templates to simplify both implementing and maintaining the actual code that does the work but to provide a C interface, you'll still need to explicitly instantiate the functions for the types you aim to support.
If you'd like a C++ user to have the same restricted access to the functions as a C user will have, you can move the template implementation into the .cpp file and do the explicit instantiation there. A C++ user trying to use the function with types for which you have not explicitly instantiated the template will get a linking error.
It could look something like this:
// a.hpp
#pragma once
template <class T>
T addStuff(const T& a, const T& b); // no implementation here.
// a.cpp
#include "a.hpp"
#include "a.h"
template <class T>
T addStuff(const T& a, const T& b) {
T rv = a;
rv += b;
return rv;
}
// C interface - note: it's inside the .cpp file
extern "C" {
int add_ints(int a, int b) {
return addStuff(a, b);
}
double add_doubles(double a, double b) {
return addStuff(a, b);
}
}
/* a.h */
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int add_ints(int, int);
double add_doubles(double, double);
#ifdef __cplusplus
}
#endif
A C user can now include the .h file and call the two functions for which you've provided an implementation.
Example:
// main.c
#include "a.h"
#include <stdio.h>
int main() {
printf("%d\n", add_ints(10, 20));
printf("%f\n", add_doubles(3., .14159));
}
Compilation:
g++ -c a.cpp
gcc -o main main.c a.o

C++ redeclaration inconsistency/interestingness

I was answering this question when I thought of this example:
#include <iostream>
void func(int i);
void func();
int main (){
func();
return 0;
}
void func(){}
In the above example, the code compiles fine. However, in the below example, the code does not compile correctly:
#include <iostream>
void func();
int func();
int main (){
func();
return 0;
}
void func(){}
This is the error that occurs when this code is compiled (in clang++):
file.cpp:4:5: error: functions that differ only in their return type cannot be
overloaded
int func();
I would expect an error like this both times.
I fiddled around with the code a bit, and for some completely odd reason, it seems that the linker completely ignores incorrect declarations. Now this allows for some very weird code. For example this header file would be legal:
#ifndef EXAMPLE
#define EXAMPLE
void func();
void func(int a);
void func(int b);
void func(int a, int b);
void func(int a, short b);
void func(int w);
void func(short b);
#endif
Why? Why in the world does any of this work? Is this just a C++ standard failure? Compiler failure? "Feature"? Actual Feature? (That is all one question by the way.)
P.S. While I'm waiting for an answer, I'm going to be over here taking advantage of this for pre-adding features in code that will probably end up in production.
The first is function overload, argument names are not taken into account (argument types or its count are different).
The second is function redeclaration (argument types and count are the same) with changed return type that is forbidden. Overloading of return type only is not allowed. The compiler told it to you.

Call function outside of current namespace in C++

I'm trying to call a function defined in a C file from my CPP code and I think I am having issues getting the correct namespace. When compiling I get the error: "Undefined reference to 'Get'".
My C header:
// c.h
#ifndef C_H
#define C_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
VAL_A1,
VAL_A2
} TYPE_A;
typedef enum
{
VAL_B1,
VAL_B2
} TYPE_B;
typedef enum
{
VAL_C1,
VAL_C2
} TYPE_C;
typedef struct
{
TYPE_B b;
TYPE_C c;
} TYPE_D;
TYPE_A Get(TYPE_B b, TYPE_D *d);
#ifdef __cplusplus
}
#endif
#endif
And my CPP file:
// main.cpp
...
extern "C" {
#include "c.h"
}
...
namespace MyNamespace
{
...
MyClass::MyFunc()
{
TYPE_D d;
// None of these calls will compile
// Get(VAL_B1, &d);
// ::Get(VAL_B1, &d);
}
...
}
I have tried calling without namespace reference and also with the "root" namespace using "::" with no luck. Any help is appreciated. I've read through this which seems to clarify it but I don't really understand it:
using C++ with namespace in C
"Undefined reference" means that the function has been declared (in the header), but not defined. You'll need to define the function in a source file somewhere (presumably the C file you refer to), and make sure that is linked when you build the program.
First, let's note what that error means. An undefined reference at the linker stage means that the compiler is unable to find the instance of something. In this case, the implementation of a function.
Let's look at your code.. There are a few things missing that we need to add to make it compilable:
A definition for Get().
main()
The class definition for MyClass.
Once we added those three fixes, the code compiles without error.
extern "C" { extern "C" {
typedef enum {
VAL_A1,
VAL_A2
} TYPE_A;
typedef enum {
VAL_B1,
VAL_B2
} TYPE_B;
typedef enum {
VAL_C1,
VAL_C2
} TYPE_C;
typedef struct {
TYPE_B b;
TYPE_C c;
} TYPE_D;
TYPE_A Get(TYPE_B b, TYPE_D *d) {
return VAL_A1;
}
}}
namespace MyNamespace {
struct MyClass {
void MyFunc();
};
void MyClass::MyFunc() {
TYPE_D d;
Get(VAL_B1, &d);
::Get(VAL_B1, &d);
}
}
int main() {}
The definition of Get (not shown in the question) also needs to be enclosed in extern "C".
The main difference between C and C++ functions, in practice, is the way they are named in the executable format. C++ functions get "name mangling" treatment by the linker but C functions do not. The linker will see the C++ definition of Get and it will have no idea of its relation to the C declaration, even if they have the same signature.

using a template function as dll in another project

I have a simple function like this:
cusp.dll
#define EXPORT extern "C" __declspec (dllexport)
EXPORT
void cuspDsolver(int *r, int *c, double *v, double *x, double *b, int size, int nnz,double tol)
{
.
.
.
.
.
}
and I created a dll using these two lines:
#define EXPORT extern "C" __declspec (dllexport)
EXPORT
and I called this function in other Project using this method:
HINSTANCE hDLL = LoadLibrary("C:\\Users\\Administrator\\Documents\\Visual Studio 2012\\Projects\\Ardalan_12\\cusp.dll");
if(hDLL == NULL)
{
cout<< "Failed to load DLL" <<endl;
}
typedef void(*fnPtr)(int *, int *, double *, double *, double *, int , int ,double);
fnPtr pfn;
pfn=(fnPtr)GetProcAddress(hDLL,"cuspDsolver");
if(pfn)
{
pfn(rowOffset,colIndex,values,answer,rightHandSide,theSize,nnz,0.9);
}
FreeLibrary(hDLL);
this works very fine, but now I changed my function to this
//#define EXPORT extern "C" __declspec (dllexport)
//EXPORT
template <typename LinearOperator,typename Vector>
void cuspDsolver(LinearOperator& A,Vector& X,Vector& B,double tol)
{
cusp::default_monitor<double> monitor(B, 10000, tol);
cusp::precond::scaled_bridson_ainv<double,cusp::device_memory> PRE(A);
DWORD dw1 = GetTickCount();
cusp::krylov::cg(A,X,B,monitor,PRE);
DWORD dw2 = GetTickCount();
double dw3 = dw2 - dw1;
cout <<endl << "time spent is : " << dw3 << endl;
cout << endl << "developed by cusp!!!" << endl;
}
but Visual Studio won't allow extern "C" __declspec (dllexport) with template functions is there any way to do this easily?actually I'm not expert,so would you please explain this to me in detail?
There is no such thing as a "template function." There is a function template, however; that is a template from which functions are created by instantiation. In this case, the distinction is important.
To call a function instantiated from a template, you must have access to that instantiation. The most common case is to implement the template in a header file and simply #include it (see this SO question for more details). I believe that you want your function to be usable with arbitrary client-supplied types as LinearOperation and Vector, so a header-only implementation is your only option.
If, on the other hand, you know all the types you would want to instantiate the template with when building your library, you can actually explicitly instantiate the template for those types and export these explicit instantiations. Like this:
Header file
template <typename LinearOperator,typename Vector>
void cuspDsolver(LinearOperator& A,Vector& X,Vector& B,double tol);
Source file
template <typename LinearOperator,typename Vector>
void cuspDsolver(LinearOperator& A,Vector& X,Vector& B,double tol)
{
// body here
}
template __declspec(dllexport) void cuspDsolver(MyConcreteOperator1& A, MyConcreteVector1& X, MyConcreteVector1& B, double tol);
template __declspec(dllexport) void cuspDsolver(MyConcreteOperator2& A, MyConcreteVector2& X, MyConcreteVector2& B, double tol);
// etc.
Such instantiations cannot be extern "C", however (they all have the same function name, after all). So if you want to load them dynamically, you'll have to provide uniquely-named C-linkage accessors to them.
Still, I believe what you're really looking for is implementing the funciton in a header file.
Based on your comments, here is how you could actually make your library dynamically loadable while using CUSP internally.
You cannot have a function template in your library's public interface. So let's say you want to allow using your library with the following types of LinearOperator: OperatorCharm and OperatorTop, and with the following types of Vector: FancyVector<float> and FancyVector<double>. Then, your public interface could look like this:
template <typename LinearOperator,typename Vector>
void cuspDsolver(LinearOperator& A,Vector& X,Vector& B,double tol)
{
// body
}
EXPORT void cuspDsolver_Charm_float(params_which, correspond_to, OperatorCharm_and, FancyVector_of_float)
{
cuspDsolver(params);
}
EXPORT void cuspDsolver_Charm_double(params_which, correspond_to, OperatorCharm_and, FancyVector_of_double)
{
cuspDsolver(params);
}
EXPORT void cuspDsolver_Top_float(params_which, correspond_to, OperatorTop_and, FancyVector_of_float)
{
cuspDsolver(params);
}
EXPORT void cuspDsolver_Charm_double(params_which, correspond_to, OperatorTop_and, FancyVector_of_double)
{
cuspDsolver(params);
}
You don't even have to instantiate the template explicitly any more, since it will be instantiated implicitly for the calls in the EXPORT-ed functions.
So in effect, your public API will be those 4 cuspDsolver_a_b functions, which can be queried dynamically as normal.
Template functions are not compiled and thus not part of a DLL as there's an infinite number of function derived from a template.
Only specific instances of the template are compiled and linked into a binary. You can expose those specialized template functions in a DLL. You'll need a header file for those names as string them in a hardcoded string is problematic.
If you want to use a template function w/o specializing it, export it through a header file.