Page 1 of 1

Calling a mangled template in C

Posted: Fri Aug 12, 2016 8:26 pm
by BringerOfShadows
I am wanting to develop an OS using a mix of ASM, C, and C++. However, I am unsure of how I would call a C++ template function from C. I have included an example function that I would want to use below:

Code: Select all

template <class T>
T *memcpy(T *dest, T *src, int count)
{
	int i;
	for(i=0; i < count; i++)
	{
		*dest = *src;
	}
	return dest;
}
Can anyone either tell me how I would go about calling this function in C, or point me some where that can explain this?
P.S. I am aware of name mangling.

Re: Calling a mangled template in C

Posted: Fri Aug 12, 2016 9:03 pm
by alexfru

Re: Calling a mangled template in C

Posted: Fri Aug 12, 2016 10:15 pm
by BringerOfShadows
Not quite what I meant. Though I did just realize that I named this topic badly. What I meant was, if I know the mangled name of a function, how do I pass arguments when I am calling the fuction from C?

Re: Calling a mangled template in C

Posted: Sat Aug 13, 2016 12:12 am
by alexfru
I'd expect, the same way as usual, except for name mangling. You can always look at the (dis)assembly of the instantiated function.

Re: Calling a mangled template in C

Posted: Sat Aug 13, 2016 2:27 am
by BringerOfShadows
I would expect the same as well. However, I do not know how C language function call really looks in assembly, though I could probably find out quickly if I wanted to. In any case, I realized that it doesn't really matter as all of my non-assembly source files will be run through g++, so that would take care of the whole name mangling problem on it's own. Thanks for the help though.

Re: Calling a mangled template in C

Posted: Sat Aug 13, 2016 3:12 am
by gerryg400
The best way, in my opinion is to write your 'c' in a cpp file and compile it with g++. Then it all just works.

Re: Calling a mangled template in C

Posted: Sat Aug 13, 2016 6:02 am
by mariuszp
you can't really do that because functions with templates will always be inlined, possibly unless you have a specialized version.

Re: Calling a mangled template in C

Posted: Sat Aug 13, 2016 12:52 pm
by BringerOfShadows
gerryg400 wrote:The best way, in my opinion is to write your 'c' in a cpp file and compile it with g++. Then it all just works.
I figured that would be the best way. If I fo it all through g++, the name mangling problem takes care of itself. I just have to be careful that I make any function that would be called in my assembly code is linked in c-style.

Though I have to ask, if I have a c-style function, and I have it call a c++ function, does the called function have to be explicitly stated as a c++ function?

I.e.

Code: Select all

extern "C" void print (string x)
{
std::cout << x << std::endl;
return;
}
Would the cout and endl functions be called c-style or c++ style?