Pass a function body from C to C++ - c

Not sure if this is even possible.
I need to pass a function from C to C++.
It cannot be a function pointer.
C++ Function that I need to call:
template<class Lam>
void parfor(int N, Lam lam) {
lam(i);
}
C Function that I want to give to parfor (ptr can be a global pointer here):
void calc(int num) {
ptr[0] = num;
}
C Main to look like this:
include <ParFor.hpp>
parfor(calc, 1);
I could put my function definitions inside a header. On the C++ side I have a function (from an outside library) that takes a C++ lambda or a C++ functor. It's templated to a lambda
My current thinking is put my C functions inside a file, compile LLVM IR for them and somehow force inline the IR generated by clang into my C++ function.
C calls mycppfunc(mycfunc). mycppfunc has the LLVM IR for mycfunc and is able to generate proper code.
I tried this but but compiler crashes at link stage due to what seems to be incompatible IRs.

From the code snippets and the comments I understand that you attempt to launch a C kernel using a SYCL parallel_for.
From an official support perspective, since the SYCL device compiler is by definition a C++ compiler (as SYCL is a programming model based on C++), the kernel code must be parsed as C++ code. I don't think there's any official way to achieve any more interoperability with C code than to just try to compile it as C++ by the device compiler. However, I have the impression that you are more interested in experimenting with interoperability beyond this as a research project.
For this, injecting IR might be a path worthy of investigation but I don't think that it will be straight-forward. Depending on which SYCL features you use, the device compiler might need to perform additional IR transformations to achieve correct semantics. So, you might have to replicate these transformations in order to inject your IR. You might end up reinventing a SYCL compiler for C...
Since any more in-depth discussion about this requires extensive knowledge of the internal implementation details of your SYCL implementation, I would suggest that you contact the developers of your implementation directly for clarification.

Related

Does C has any built in functions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
There are around 50 built in functions in Python. The printf and scanf functions of C is comes under stdio.h library.
Are there any functions in C that are the part of language itself?
C has a few keywords, but no built-in functions. Every function you use comes from some other library. It is possible to compile a program even without the standard library using -nostdlib flag (for gcc).
It depends on what you mean by "part of the language". There are specifications that define what the C standard library should offer, so to that extent printf(), etc., are "part of the language".
However, a C compiler won't generate the code that implements these functions -- they are expected to be provided in a library of some kind. Most C compilers will know where/what the library is, and will be configured to link it automatically. You can almost certainly tell the compiler/linker not to do this, if you don't want to use the standard library. There are sometimes good reasons to.
Although there is a specification for a standard library, the language syntax itself has little-to-no coupling to the library. In Java, for example, if you add a String and an object, the compiler will generate code to call the object's toString() method. This method has to exist, because the Java language and the Java runtime library are closely related.
There's no real equivalent to this process in C -- C compilers can generate code in complete ignorance of what functions might be available. Those functions do need to be made available before runtime, but that's really the job of the linker, rather than the compiler.
However, gcc at least does have a notion of "built-in" functions. For example, if I try to compile this:
void printf (void)
{
}
I get a warning:
test.c:1:6: warning: conflicting types for built-in function
‘printf’; expected ‘int(const char *, ...)’ [-Wbuiltin-
declaration-mismatch]
even if I use the -nostdlib switch. Even with no standard library, gcc still thinks of printf() as being "built-in" even though it doesn't generate code for it.
I guess that notion of a "built-in function" isn't entirely clear-cut.
All C standard library functions are built into the language—they are part of the C language as defined by the C standard. C implementations (notably compilers) may implement these functions either as built-in functions implemented by the compiler or as object modules linked in by the linker. The C standard largely separates the rules that says how C programs must behave from rules about how C programs must be implemented.
In the sense of how a C program must behave, there is no difference between a built-in function or a linked-in function: The function behaves the same, and there is no way to describe an observable difference between the two implementations.
Compilers generally use a mix of built-in implementations and linked-in implementations. For example, in void foo(uint32_t u) { float f; memcpy(&f, &u, sizeof f); … }, a compiler may implement the memcpy by generating an instruction to move data from an integer register to a floating-point register and not by calling any external memcpy routine. For other memcpy calls, it might generate simple instructions to move bytes and again not call an external routine. For sqrt, it might generate a square-root instruction if the target machine has an appropriate one.
More complicated functions are more often implemented by calling external functions that are linked into the program after compilation. Even with many of these, the compiler may recognize special cases and provide calls to alternative functions (printf("Hello, world.\n") may be implemented as if it were puts("Hello, world."), instructions that perform the function without a call (pow(x, 2) may be implemented as a multiplication of x by itself), or results may be computed at compile time, by code built into the compiler (sin(.3) might be evaluated at at compile time).

Do any C-targeting compilers allow inline C?

Some C compilers emit assembly language and allow snippets of assembly to be placed inline in the source code to be copied verbatim to the output, e.g. https://gcc.gnu.org/onlinedocs/gcc/Using-Assembly-Language-with-C.html
Some compilers for higher-level languages emit C, ranging from Nim which was to some extent designed for that, to Scheme which very definitely was not, and takes heroic effort to compile to efficient code that way.
Do any such compilers, similarly allow snippets of C to be placed inline in the source code, to be copied verbatim to the output?
I'm not sure I understand what you mean by "be copied verbatim to the output," but all C compilers (msvc, gcc, clang, etc...) have preprocessor directives that essentially allow snippets of code to be added to the source files for compilation. For example, the #include directive will pull in the contents the specified file to be included in compilation. An "effect" of this is that you can do weird things such as:
printf("My code: \n%s\n",
#include "/tmp/somefile.c"
);
Alternatively, creating macros with the #define directive allows you to supplant snippets of code by calling a macro name. This all happens at the preprocessor stage before turning into the compile "output."
Other languages, like c# with roslyn, allows runtime compilation of code. Of course, you can also implement the same within c by calling your compiler as via something like system() and then loading the resulting library with dlopen.
Edit:
Now that I come back and think about this question, I should also note that python is one of those C-targeting "compilers" (I guess technically a interpreter on top of the python runtime). Python let's you use native C compiled code with some either some py API code to export functions or directly with some dlopen-like helpers. Take a look at the inlinec module that does what I described above (call the compiler then load the compiled code). I suppose you should have the ability to do similar functionality with any language that can call c compiled code (c#, java, etc...).

Should a Fortran-compiled and C-compiled DLL be able to import interchangeably? (x86 target)

The premise: I'm writing a plug-in DLL which conforms to an industry standard interface / function signature. This will be used in at least two different software packages used internally at my company, both of which have some example skeleton code or empty shells of this particular interface. One vendor authors their example in C/C++, the other in Fortran.
Ideally I'd like to just have to write and maintain this library code in one language and not duplicate it (especially as I'm only just now getting some comfort level in various flavors of C, but haven't touched Fortran).
I've emailed off to both our vendors to see if there's anything specific their solvers need when they import this DLL, but this has made me curious at a more fundamental level. If I compile a DLL with an exposed method void foo(int bar) in both C and Fortran... by the time it's down to x86 machine instructions - does it make any difference in how that method is called by program "X"? I've gathered so far that if I were to do C++ I'd need the extern "C" bit to avoid "mangling" - there anything else I should be aware of?
It matters. The exported function must use a specific calling convention, there are several incompatible ones in common use in 32-bit code. The calling convention dictates where the function arguments are stored, in what order they are passed and how they are removed again. As well as how the function return value is passed back.
And the name of the function matters, exported function names are often decorated with extra characters. Which is what extern "C" is all about, it suppresses the name mangling that a C++ compiler uses to prevent overloaded functions from having the same exported name. So the name is one that the linker for a C compiler can recognize.
The way a C compiler makes function calls is pretty much the standard if you interop with code written in other languages. Any modern Fortran compiler will support declarations to make them compatible with a C program. And surely this is something that's already used by whatever software vendor you are working with that provides an add-on that was written in Fortran. And the other way around, as long as you provide functions that can be used by a C compiler then the Fortran programmer has a good chance at being able to call it.
Yes it has been discussed here many many times. Study answers and questions in this tag https://stackoverflow.com/questions/tagged/fortran-iso-c-binding .
The equivalent of extern "C" in fortran is bind(C). The equivalency of the datatypes is done using the intrinsic module iso_c_binding.
Also be sure to use the same calling conventions. If you do not specify anything manually, the default is usually the same for both. On Linux this is non-issue.
extern "C" is used in C++ code. So if you DLL is written in C++, you mustn't pass any C++ objects (classes).
If you stick with C types, you need to make sure the function passes parameters in a single way e.g. use C's default of _cdecl. Not sure what Fortran uses.

Looking for a way to access c++ objects in C as if I was in c++

I have a few ideas:
char* test = "testInteger(5).workOnReturn("doIt")[10]"
int ret = execute(test);
What if I use the 'extern' keyword?
Suppose I have a whole bunch of C++ implementations and classes.
Couldn't I just define the same things in C with 'extern' and provide a dummy implementation and on runtime, it would access the C++ library with the actual implementation?
Perhaps you could customize your GCC compiler (e.g. with a MELT extension) to produce somehow a C interface to your library (perhaps by annotating relevant C++ functions with your own #pragma-s ....)
But your question is too vague to get a more precise answer.
What is your C++ library, how should it be used in C++?
Look at how other C++ libraries interface to C; e.g. look inside the source code of PPL
If you want to use C++ from C, it can be done only in an extremely limited way, and as far as the C++ code is explicitly built for it (that means basically throwing away most for what makes C++ C++). Won't happen in your case.
Your ways out are to just use C++ or get a library for C. Anything else will hurt too much to make any sense.

Linking against libraries from LLVM IR

Currently I'm playing around with LLVM and am implementing my own toy compiler and programming language. Are there any good tutorials or examples on how I can call external library functions (e.g. from libc or whatever) from the IR decomposition of my own language?
Cheers
You'll need to declare the functions you want to call in the LLVM IR. If you don't provide a body for a function, it works just like a declaration in C. You're probably aware of this, but the linker only checks the function name, not the type. Make sure you match the types up in the declaration or you'll get some strange results and no warnings.

Resources