Sign in to follow this  
Khaos

Converting C++ macros to C#

Recommended Posts

I am in the process of converting a program made in C++ to C# and .NET. This, however, includes some C++ macros that I do not know how to deal with. Would C++ macros be converted into C# functions, or what is the best bet? I want to eliminate the macros but keep their functionality. Here they are:
#define ASSERT_STACK_ELEMENTS(x) if (stackPointer < x) { error = STACK_VIOLATION; break; }

#define ASSERT_STACK_NOT_FULL if (stackPointer == STACK_DEPTH) { error = STACK_VIOLATION; break; }

#define PUSH(x) (stack[stackPointer++] = x)
#define POP (stack[--stackPointer])
#define PEEK (stack[stackPointer-1])
First off, I'd love to know what these macros mean. I am familiar with C++, but I never got into macros. What is the point of them, over something.. else? How do these macros work? Secondly, how can I convert these macros into solid C# code? I am guessing I would need their function equivalent, but I do not know it. Any help or ideas? Thank you much.

Share this post


Link to post
Share on other sites
They look like they were part of a badly written virtual machine.

I don't know C#, but macros in C++ substitute text. If you to write PUSH(5) in your program, the preprocessor would replace it with (stack[stackPointer++]=5) and then the result would get compiled.

Share this post


Link to post
Share on other sites
The macros looks like some kind of array-based stack, with
the array (named "stack") probably a global variable.

I'd imagine that you can just use the System.Collections.Stack
to replace those macros... by using a proper stack class.

Share this post


Link to post
Share on other sites
Quote:
Original post by smart_idiot
I don't know C#, but macros in C++ substitute text. If you to write PUSH(5) in your program, the preprocessor would replace it with (stack[stackPointer++]=5) and then the result would get compiled.

Like this:

int main()
{
PUSH(5);
return 0;
}

Becomes:

int main()
{
(stack[stackPointer++] = 5);
return 0;
}


You can also create a function to replace the macro:

void AssertStackElements( int x )
{
if ( stackPointer < x )
{
error = STACK_VIOLATION;
break;
}
}

Those macros are bad macros though. stackPointer, STACK_VIOLATION, and error are undeclared; and a break in an if statement!?
So you pretty much have to rewrite the code.

PS:
I'm loving this new source tag, it's small and doesn't take up much space as it used to. but lol, only in Mozilla. It's still a big huge box in IE.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this