0

I am creating a game in c++ using the SDL library. To keep everything readable and orderly, I make a dll from the actual game program, the menu's program and have only the main program as an executable. In the main program I create a struct that holds all screen information, such as standard colors, the width and height of the screen, fonts and the renderer, window and surface object of the screen. In the main program I initialise one instance of this struct. A pointer to this instance is passed as a parameter to the functions and objects in the dll's. The colors are defined in a std::map<char*, int>. To access the colors, one could use something like this:

struct screen{
    std::map<char*, Uint32> colors;
}

screen display;

std::pair<char*, Uint32> color;
color.first = "green";
color.second = 0x00FF00;
display.colors.insert(color);

int x = display.colors["green"] //for example

Reading the values in the main executable works fine, but having the screen object passed as a pointer to a function inside a dll, it returns a NULL. As a pointer, I read the value like this:

void function(screen* display){
    Uint32 x = display->colors["green"];
}

When doing the following:

std::map<char*, int>::iterator i = display->colors.begin();
while(i->first != "green"){
    i++
}
int x = i->second;

There seems to be no problem. But I want to be able to use the first method in the dll's, since the second method is much less efficient.

Why doesn't the first method work in dll's? and how do I get it to work in the dll's? I use visual studio 2012.

D-Inventor
  • 450
  • 5
  • 23

2 Answers2

1

The pointer issue I told you about is probably the reason for your problem. In the executable the string literal "green" has one address, and in the DLL the string-literal "green" has a totally different address. Yes the strings will be equal if you compare them, but the pointers themselves will not be the same, leading to your problem.

The answer is simply to use std::string as the key.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You should question yourself what "green" as a char* points to. Without using the DLL, being just one compilation unit gives "green" a single address which will be reused during the program. So, the pointer is the same when getting and retrieving from the map. When you compile the DLL, the "green" pointer is a different pointer than the "green" pointer from the main executable, so you cannot retrieve it from the map.

perencia
  • 1,498
  • 3
  • 11
  • 19