0

I am using x64asm code in my C++ project. I am using this code to access my function that is defined in .asm file:

extern "C" void strpl(char* , int*, bool )

what I want is it to have any type pf pointer at first argument instead of just char*

I tried custom template which I googled like so:

template<typename T>
extern "C" void strpl(T const* , int*, bool )

but it says custom type are incompatible with extern "C"

what should I do to have it pass pointer of any type as first argument

1 Answers1

1

I believe a raw void pointer (void*) would be sufficient.

You can use C-style casts to convert to and from void pointers to pointers of other primitive types in your calling C/C++ code.

Some advice... The use of templates is overkill for what you're trying to accomplish and it takes a lot of understanding to get templates right. There are solutions that don't require templates, so avoid them until it's necessary.

psyklopz
  • 2,283
  • 4
  • 24
  • 29
  • awesome it works. One more this can i use void* in normal functions to get pointer of any type? I mean the inline C++ function. I used template and it works but I was just wondering – PeaceBeUponYou Jul 06 '21 at 05:13
  • You can cast any pointer to a `void*`. It's a powerful tool, but it's deadly too. I suggest using it only when you need to leave the land of C++, like when passing data through a function that has `extern "C"` linkage. When you are within C++ land, use typed raw pointers. This allows the compiler to keep you safe. As an aside, (I'm not sure of your dev environment), but if you've got access to the STL, I'd further recommend using smart pointers over raw ones, like `std::unique_ptr` and `std::shared_ptr` whenver possible. These modern features in the language are there to protect you. – psyklopz Jul 06 '21 at 05:31
  • @PeaceBeUponYou: Yes, but beware the strict-aliasing rule. If your function does `* (int*) ptr` to dereference the `void*` as an `int*`, it's only safe to pass it pointers to actual `int` objects (i.e. that the rest of your code accesses as `int`, or via `char*`). However, if you use `memcpy`, you're allowed to read the bytes of any object, so you can `memcpy(&my_int, p, sizeof(my_int))` to do an unaligned aliasing-safe load of an `int` from any address. Modern compilers inline memcpy as a single instruction, at least on ISAs where unaligned loads are allowed. – Peter Cordes Jul 06 '21 at 05:31
  • @PeaceBeUponYou: See also [Why does unaligned access to mmap'ed memory sometimes segfault on AMD64?](https://stackoverflow.com/q/47510783) and [Why does glibc's strlen need to be so complicated to run quickly?](https://stackoverflow.com/a/57676035) re: pointer-casting with unaligned and/or aliasing loads and how to keep compilers happy. – Peter Cordes Jul 06 '21 at 05:33
  • Thanks for pointing this out Peter. You are absolutely right, OP needs to keep this in mind. – psyklopz Jul 06 '21 at 05:37