問題描述
是否可以在 C++ 結構中編寫靜態程序集數據? (Is it possible to write static assembly data in C++ struct?)
I'm trying to declare a static const data using asm syntax inside of a struct.
Maybe something like this?
struct Z
{
public:
static char hello[] = asm volatile(".ascii \"Hello\"");
};
Note that this does not come even close to working. :) And my assembly is super rusty.
EDIT:
For those interested in this question and the reasons behind it, please see store non‑nul terminated C string constant in C++.
This question was tangential and I didn't want to clutter that question up with it as well as it could have other uses beyond what I wanted it for which is why I started up a separate question.
Thanks for your interest and help.
參考解法
方法 1:
No, not like this. You can make inline assembly if your compiler supports it, however. Another common (and likewise non‑portable) technique is to use an assembler to assemble the code to raw machine code, then wrap it into a byte array (you can see this in action in various kinds of shellcode where the payload is stored like this).
方法 2:
You comment says you want to "generate a string of bytes that is not null terminated". That is easy, use
char hello[] = { 'H', 'e', 'l', 'l', 'o' };
方法 3:
Assuming you know (or can count) the size of the string:
char hello[5] = "Hello";
will do exactly what you want.
You could also do a macro, like this:
#define STR(x, y) const char x[sizeof(y)‑1] = y
This works for me:
#include <stdio.h>
#define STR(x, y) const char x[sizeof(y)‑1] = y
STR(hello, "Hello");
STR(hello2, "Hello World");
STR(hello3, "Hello kerflunk");
#define PRINT(x) printf("size " #x "=%zd\n", sizeof(x));
int main()
{
STR(bar, "Bar");
PRINT(hello);
PRINT(hello2);
PRINT(hello3);
PRINT(bar);
return 0;
}
Output:
size hello=5
size hello2=11
size hello3=14
size bar=3
(by Adrian、user529758、brian beuning、Mats Petersson)