cstring

Providing strings for functions without quotes in C


So, I know this is not the best way to start a question-- I am guessing the answer already is 'no'.

But I will give it a shot anyways in case someone happens to know some 'black magic' that could be applied.

I am trying to design a function in C that basically takes a string as input, and then is parsed to get the relevant data out of it.

In this case, that function is 'Tensor', so you can do something like the following:

a = Tensor("[[1,2], [3,4]]")

Or

b = Tensor("[1, 2, 3, 4]")

Or

c = Tensor("[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]")

Basically any reasonable combination, but the code into the function is being processed as a string.

Yet, I am wondering if there is any way I can process this, but be able to drop the 'outer quotes' of the string, so it would be a bit more like using Python. (It just isn't 'elegant' in the current state)

Or from the first example, what I'd like is:

a = Tensor([[1,2], [3,4]])

Even if I had to inject a bit of assembly code to do this, that would be 'okay'.

Just didn't know if anyone had any 'wild ideas' on this topic.

But I have no idea how to do this.


Solution

  • #define Tensor(...) Tensor(#__VA_ARGS__)
    

    Macro replacement in C is not recursive, so Tensor will not be macro-processed again after the first replacement.

    Declare and define the Tensor function before defining this macro or use #undef to remove the macro before any declaration or definition of the function (and redefine the macro afterward if necessary).