What is #define NAME ((LPCSTR) 5) ? - c

What does this line of code mean?
#define NAME ((LPCSTR) 5)
If I define a variable, NAME *tmp, then use it like this:
((LPCSTR) 5) *tmp;
What does that code do?
Note: LPCSTR is typedef __nullterminated CONST CHAR *LPCSTR

That's a simple cast, it converts 5 to a character pointer (__nullterminated CONST CHAR *)
That's probably undefined behaviour by the standard, but sometimes used in real life.
To address specific physical addresses on your machine - for example the kernel has to do this to configure cards, onbard chips, etc...
To send special values in arguments or return values.. for example the call normally expects a pointer in the second argument, but if you pass "5" it meants something else.
As you can see, it's really a pointer, so what you've tried, NAME *tmp;, won't compile.

Given the LPCSTR type, I'm guessing this is being used to load a resource in an EXE file:
#define MAKEINTRESOURCE(x) ((LPCTSTR)(x)) // in windows.h
#define IDR_FOO 1 // usually in IDE-generated resources.h
HRSRC res = FindResource(NULL,
MAKEINTRESOURCE(IDR_FOO),
MAKEINTRESOURCE(IDR_FOO));
This is commonplace in WinAPI apps, but I've never seen someone perform the cast themselves rather than use the standard MAKEINTRESOURCE macro.

Related

How do I access any kernel symbol in a kernel module?

I am wanting to use the function getname in my kernel module. It is not exported. Since I am running into this problem right now, I would like to know how to access and use any kernel symbol that is not exported. I figure that the steps necessary to use one will differ depending what the symbol is, so I'd like to see how it would be done for a type (e.g., a struct), a variable, a table of pointers (like the system call table), and a function. How can these be done in either of these cases:
When I know the address of the symbol from System.map or /proc/kallsyms.
When I know the name of the symbol and want to use kallsyms_lookup_name in retrieving it.
I currently know how to hijack system calls and this requires declaring something like
asmlinkage <return_type> (*<name_for_system_call>)(<the types of the its arguments separated by commas>);
Would something like that be used? In this answer to another question, the example presented by the poster is
#include <linux/kallsyms.h>
static void (*machine_power_off_p)(void);
machine_power_off = (void*) kallsyms_lookup_name("machine_power_off");
But what if the symbol returns a pointer? Would I place an asterisk to the left of (*machine_power_off_p)?
#include <linux/fs.h> declares extern struct filename *getname(const char __user *);. A pointer to this function has type struct filename *(*)(const char __user *). If declaring a variable of that type, the variable name goes after the * in (*). So you can declare a variable of that type and assign the return value of kallsyms_lookup_name("getname") to it as follows:
static struct filename *(*getname_p)(const char __user *);
/* within a function body... */
getname_p = (struct filename *(*)(const char __user *))
kallsyms_lookup_name("getname");
For your other case where you want to use a numeric address, just replace the kallsyms_lookup_name function call with the actual number (kallsyms_lookup_name returns the symbol value as a number anyway).
EDIT 2021-01-19
The GCC typeof extension can be used to copy the prototype of getname from #include <linux/fs.h> to the getname_p pointer as follows:
#include <linux/fs.h>
static typeof(&getname) getname_p;
/* within a function body... */
getname_p = (typeof(&getname))kallsyms_lookup_name("getname");
EDIT 2021-05-17
From the 5.7 kernel onwards kallsyms_lookup_name and kallsyms_on_each_symbol are no longer exported to loadable kernel modules.
Accessing not exported function doesn't differ from accessing exported functions, except that you can't resolve its address in kernel. You can do trick like this:
static void (*your_func)(void);
your_func=0xhex_addr;
or for struct
strucr your_struct{int i;double j} *stru;
stru=0xhex_addr;
Type of a pointer just defines how many bytes would be read or written from or to pointer's address.
For structure or variable hex address even may reside in kernel code segment, but you'll get segmentation fault if you'll try to write something to that struct or var - reading would be legit. And one more thing... when doing this trick with structure don't forget about structure data alignment.

Determining to which function a pointer is pointing in C?

I have a pointer to function, assume any signature.
And I have 5 different functions with same signature.
At run time one of them gets assigned to the pointer, and that function is called.
Without inserting any print statement in those functions, how can I come to know the name of function which the pointer currently points to?
You will have to check which of your 5 functions your pointer points to:
if (func_ptr == my_function1) {
puts("func_ptr points to my_function1");
} else if (func_ptr == my_function2) {
puts("func_ptr points to my_function2");
} else if (func_ptr == my_function3) {
puts("func_ptr points to my_function3");
} ...
If this is a common pattern you need, then use a table of structs instead of a function pointer:
typedef void (*my_func)(int);
struct Function {
my_func func;
const char *func_name;
};
#define FUNC_ENTRY(function) {function, #function}
const Function func_table[] = {
FUNC_ENTRY(function1),
FUNC_ENTRY(function2),
FUNC_ENTRY(function3),
FUNC_ENTRY(function4),
FUNC_ENTRY(function5)
}
struct Function *func = &func_table[3]; //instead of func_ptr = function4;
printf("Calling function %s\n", func->func_name);
func ->func(44); //instead of func_ptr(44);
Generally, in C such things are not available to the programmer.
There might be system-specific ways of getting there by using debug symbols etc., but you probably don't want to depend on the presence of these for the program to function normally.
But, you can of course compare the value of the pointer to another value, e.g.
if (ptr_to_function == some_function)
printf("Function pointer now points to some_function!\n");
The function names will not be available at runtime.
C is not a reflective language.
Either maintain a table of function pointers keyed by their name, or supply a mode of calling each function that returns the name.
The debugger could tell you that (i.e. the name of a function, given its address).
The symbol table of an unstripped ELF executable could also help. See nm(1), objdump(1), readelf(1)
Another Linux GNU/libc specific approach could be to use at runtime the dladdr(3) function. Assuming your program is nicely and dynamically linked (e.g. with -rdynamic), it can find the symbol name and the shared object path given some address (of a globally named function).
Of course, if you have only five functions of a given signature, you could compare your address (to the five addresses of them).
Notice that some functions don't have any ((globally visible) names, e.g. static functions.
And some functions could be dlopen-ed and dlsym-ed (e.g. inside plugins). Or their code be synthetized at runtime by some JIT-ing framework (libjit, gccjit, LLVM, asmjit). And the optimizing compiler can (and does!) inline functions, clone them, tail-call them, etc.... so your question might not make any sense in general...
See also backtrace(3) & Ian Taylor's libbacktrace inside GCC.
But in general, your quest is impossible. If you really need such reflective information in a reliable way, manage it yourself (look into Pitrat's CAIA system as an example, or somehow my MELT system), perhaps by generating some code during the build.
To know where a function pointer points is something you'll have to keep track of with your program. Most common is to declare an array of function pointers and use an int variable as index of this array.
That being said, it is nowadays also possible to tell in runtime which function that is currently executed, by using the __func__ identifier:
#include <stdio.h>
typedef const char* func_t (void);
const char* foo (void)
{
// do foo stuff
return __func__;
}
const char* bar (void)
{
// do bar stuff
return __func__;
}
int main (void)
{
func_t* fptr;
fptr = foo;
printf("%s executed\n", fptr());
fptr = bar;
printf("%s executed\n", fptr());
return 0;
}
Output:
foo executed
bar executed
Not at all - the symbolic name of the function disappears after compilation. Unlike a reflective language, C isn't aware of how its syntax elements were named by the programmer; especially, there's no "function lookup" by name after compilation.
You can of course have a "database" (e.g. an array) of function pointers that you can compare your current pointer to.
This is utterly awful and non-portable, but assuming:
You're on Linux or some similar, ELF-based system.
You're using dynamic linking.
The function is in a shared library or you used -rdynamic when linking.
Probably a lot of other assumptions you shouldn't be making...
You can obtain the name of a function by passing its address to the nonstandard dladdr function.
set your linker to output a MAP file.
pause the program
inspect the address contained in the pointer.
look up the address in the MAP file to find out which function is being pointed to.
A pointer to a C function is an address, like any pointer. You can get the value from a debugger. You can cast the pointer to any integer type with enough bits to express it completely, and print it. Any compilation unit that can use the pointer, ie, has the function name in scope, can print the pointer values or compare them to a runtime variable, without touching anything inside the functions themselves.

Why #defines instead of enums [duplicate]

Which one is better to use among the below statements in C?
static const int var = 5;
or
#define var 5
or
enum { var = 5 };
It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:
static const int var = 5;
#define var 5
enum { var = 5 };
Ignoring issues about the choice of name, then:
If you need to pass a pointer around, you must use (1).
Since (2) is apparently an option, you don't need to pass pointers around.
Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is.
(1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can.
(1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can.
Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5.
(1) cannot be used in places like switch statements; both (2) and (3) can.
(1) cannot be used to initialize static variables; both (2) and (3) can.
(2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that.
You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.
So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.
If you were asking about C++, then you'd use option (1) — the static const — every time.
Generally speaking:
static const
Because it respects scope and is type-safe.
The only caveat I could see: if you want the variable to be possibly defined on the command line. There is still an alternative:
#ifdef VAR // Very bad name, not long enough, too general, etc..
static int const var = VAR;
#else
static int const var = 5; // default value
#endif
Whenever possible, instead of macros / ellipsis, use a type-safe alternative.
If you really NEED to go with a macro (for example, you want __FILE__ or __LINE__), then you'd better name your macro VERY carefully: in its naming convention Boost recommends all upper-case, beginning by the name of the project (here BOOST_), while perusing the library you will notice this is (generally) followed by the name of the particular area (library) then with a meaningful name.
It generally makes for lengthy names :)
In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)
While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.
So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.
If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.
In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).
The difference between static const and #define is that the former uses the memory and the later does not use the memory for storage. Secondly, you cannot pass the address of an #define whereas you can pass the address of a static const. Actually it is depending on what circumstance we are under, we need to select one among these two. Both are at their best under different circumstances. Please don't assume that one is better than the other... :-)
If that would have been the case, Dennis Ritchie would have kept the best one alone... hahaha... :-)
In C #define is much more popular. You can use those values for declaring array sizes for example:
#define MAXLEN 5
void foo(void) {
int bar[MAXLEN];
}
ANSI C doesn't allow you to use static consts in this context as far as I know. In C++ you should avoid macros in these cases. You can write
const int maxlen = 5;
void foo() {
int bar[maxlen];
}
and even leave out static because internal linkage is implied by const already [in C++ only].
Another drawback of const in C is that you can't use the value in initializing another const.
static int const NUMBER_OF_FINGERS_PER_HAND = 5;
static int const NUMBER_OF_HANDS = 2;
// initializer element is not constant, this does not work.
static int const NUMBER_OF_FINGERS = NUMBER_OF_FINGERS_PER_HAND
* NUMBER_OF_HANDS;
Even this does not work with a const since the compiler does not see it as a constant:
static uint8_t const ARRAY_SIZE = 16;
static int8_t const lookup_table[ARRAY_SIZE] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // ARRAY_SIZE not a constant!
I'd be happy to use typed const in these cases, otherwise...
If you can get away with it, static const has a lot of advantages. It obeys the normal scope principles, is visible in a debugger, and generally obeys the rules that variables obey.
However, at least in the original C standard, it isn't actually a constant. If you use #define var 5, you can write int foo[var]; as a declaration, but you can't do that (except as a compiler extension" with static const int var = 5;. This is not the case in C++, where the static const version can be used anywhere the #define version can, and I believe this is also the case with C99.
However, never name a #define constant with a lowercase name. It will override any possible use of that name until the end of the translation unit. Macro constants should be in what is effectively their own namespace, which is traditionally all capital letters, perhaps with a prefix.
#define var 5 will cause you trouble if you have things like mystruct.var.
For example,
struct mystruct {
int var;
};
#define var 5
int main() {
struct mystruct foo;
foo.var = 1;
return 0;
}
The preprocessor will replace it and the code won't compile. For this reason, traditional coding style suggest all constant #defines uses capital letters to avoid conflict.
It is ALWAYS preferable to use const, instead of #define. That's because const is treated by the compiler and #define by the preprocessor. It is like #define itself is not part of the code (roughly speaking).
Example:
#define PI 3.1416
The symbolic name PI may never be seen by compilers; it may be removed by the preprocessor before the source code even gets to a compiler. As a result, the name PI may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 3.1416, not PI. If PI were defined in a header file you didn’t write, you’d have no idea where that 3.1416 came from.
This problem can also crop up in a symbolic debugger, because, again, the name you’re programming with may not be in the symbol table.
Solution:
const double PI = 3.1416; //or static const...
I wrote quick test program to demonstrate one difference:
#include <stdio.h>
enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};
#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32
int main(int argc, char *argv[]) {
printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
return(0);
}
This compiles with these errors and warnings:
main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
^
Note that enum gives an error when define gives a warning.
The definition
const int const_value = 5;
does not always define a constant value. Some compilers (for example tcc 0.9.26) just allocate memory identified with the name "const_value". Using the identifier "const_value" you can not modify this memory. But you still could modify the memory using another identifier:
const int const_value = 5;
int *mutable_value = (int*) &const_value;
*mutable_value = 3;
printf("%i", const_value); // The output may be 5 or 3, depending on the compiler.
This means the definition
#define CONST_VALUE 5
is the only way to define a constant value which can not be modified by any means.
Although the question was about integers, it's worth noting that #define and enums are useless if you need a constant structure or string. These are both usually passed to functions as pointers. (With strings it's required; with structures it's much more efficient.)
As for integers, if you're in an embedded environment with very limited memory, you might need to worry about where the constant is stored and how accesses to it are compiled. The compiler might add two consts at run time, but add two #defines at compile time. A #define constant may be converted into one or more MOV [immediate] instructions, which means the constant is effectively stored in program memory. A const constant will be stored in the .const section in data memory. In systems with a Harvard architecture, there could be differences in performance and memory usage, although they'd likely be small. They might matter for hard-core optimization of inner loops.
Don't think there's an answer for "which is always best" but, as Matthieu said
static const
is type safe. My biggest pet peeve with #define, though, is when debugging in Visual Studio you cannot watch the variable. It gives an error that the symbol cannot be found.
Incidentally, an alternative to #define, which provides proper scoping but behaves like a "real" constant, is "enum". For example:
enum {number_ten = 10;}
In many cases, it's useful to define enumerated types and create variables of those types; if that is done, debuggers may be able to display variables according to their enumeration name.
One important caveat with doing that, however: in C++, enumerated types have limited compatibility with integers. For example, by default, one cannot perform arithmetic upon them. I find that to be a curious default behavior for enums; while it would have been nice to have a "strict enum" type, given the desire to have C++ generally compatible with C, I would think the default behavior of an "enum" type should be interchangeable with integers.
A simple difference:
At pre-processing time, the constant is replaced with its value.
So you could not apply the dereference operator to a define, but you can apply the dereference operator to a variable.
As you would suppose, define is faster that static const.
For example, having:
#define mymax 100
you can not do printf("address of constant is %p",&mymax);.
But having
const int mymax_var=100
you can do printf("address of constant is %p",&mymax_var);.
To be more clear, the define is replaced by its value at the pre-processing stage, so we do not have any variable stored in the program. We have just the code from the text segment of the program where the define was used.
However, for static const we have a variable that is allocated somewhere. For gcc, static const are allocated in the text segment of the program.
Above, I wanted to tell about the reference operator so replace dereference with reference.
We looked at the produced assembler code on the MBF16X... Both variants result in the same code for arithmetic operations (ADD Immediate, for example).
So const int is preferred for the type check while #define is old style. Maybe it is compiler-specific. So check your produced assembler code.
I am not sure if I am right but in my opinion calling #defined value is much faster than calling any other normally declared variable (or const value).
It's because when program is running and it needs to use some normally declared variable it needs to jump to exact place in memory to get that variable.
In opposite when it use #defined value, the program don't need to jump to any allocated memory, it just takes the value. If #define myValue 7 and the program calling myValue, it behaves exactly the same as when it just calls 7.

Pointer to #define

I was just curious to know if it is possible to have a pointer referring to #define constant. If yes, how to do it?
The #define directive is a directive to the preprocessor, meaning that it is invoked by the preprocessor before anything is even compiled.
Therefore, if you type:
#define NUMBER 100
And then later you type:
int x = NUMBER;
What your compiler actually sees is simply:
int x = 100;
It's basically as if you had opened up your source code in a word processor and did a find/replace to replace each occurrence of "NUMBER" with "100". So your compiler has no idea about the existence of NUMBER. Only the pre-compilation preprocessor knows what NUMBER means.
So, if you try to take the address of NUMBER, the compiler will think you are trying to take the address of an integer literal constant, which is not valid.
No, because #define is for text replacement, so it's not a variable you can get a pointer to -- what you're seeing is actually replaced by the definition of the #define before the code is passed to the compiler, so there's nothing to take the address of. If you need the address of a constant, define a const variable instead (C++).
It's generally considered good practice to use constants instead of macros, because of the fact that they actually represent variables, with their own scoping rules and data types. Macros are global and typeless, and in a large program can easily confuse the reader (since the reader isn't seeing what's actually there).
#define defines a macro. A macro just causes one sequence of tokens to be replaced by a different sequence of tokens. Pointers and macros are totally distinct things.
If by "#define constant" you mean a macro that expands to a numeric value, the answer is still no, because anywhere the macro is used it is just replaced with that value. There's no way to get a pointer, for example, to the number 42.
No ,It's Not possible in C/C++
You can use the #define directive to give a meaningful name to a constant in your program
We can able to use in two forms.
Please : See this link
http://msdn.microsoft.com/en-us/library/teas0593%28VS.80%29.aspx
The #define directive can contain an object-like definition or a function-like definition.
Iam sorry iam unable to provide one more wink ... Please see the IBM links..since below i pasted linke link
u can get full info from above 2 links
There is a way to overcome this issue:
#define ROW 2
void foo()
{
int tmpInt = ROW;
int *rowPointer = &tmpInt;
// ...
}
Or if you know it's type you can even do that:
void getDefinePointer(int * pointer)
{
*pointer = ROW;
}
And use it:
int rowPointer = NULL;
getDefinePointer(&rowPointer2);
printf("ROW==%d\n", rowPointer2);
and you have a pointer to #define constant.

char array to LPCTSTR conversion in c

Does anyone know how to convert a char array to a LPCTSTR in c?
Edit:
For more reference, I need to add an integer to a string then convert that string to LPCTSTR for the first parameter of the windows function CreateFile().
This is the hardcoded example which I am currently using, but I need to be able to pass in any number to use as a port number.
CreateFile(_T("\\\\.\\COM11")... //hardcoded for com port 11
and here are several things I have tried, which I believe include the following suggestions for the next 2 answers of this post. They don't work unfortunately. If anyone could point out something I've done wrong and could possibly solve my problem, I'd appreciate it.
All of these examples assume that portNum is an int that is already assigned a valid value
1
char portName[12] = { 0 };
sprintf_s( portName, sizeof( portName ), "\\\\.\\COM%i", portNum );
CreateFile(portName...
I've also tried #1 with a LPCSTR case for what it's worth...
2
LPCSTR SomeFunction(LPCSTR aString) {
return aString;
}
main() {
char portName[12] = { 0 };
sprintf_s( portName, sizeof( portName ), "\\\\.\\COM%i", portNum );
LPCSTR lpPortName = SomeFunction(portName);
CreateFile(lpPortName...
3
const char * portName = "";
sprintf_s( portName, sizeof( portName ), "\\\\.\\COM%i", portNum );
LPCSTR lpPortName = portName;
CreateFile(lpPortName...
You can implicitly convert a char array to an LPCSTR without any casts:
void SomeFunction(LPCSTR aString);
...
char myArray[] = "hello, world!";
SomeFunction(myArray);
An LPCSTR is a Windows typedef for a long pointer to a constant string. Back in the dark days of Win16 programming, there were different types of pointers: near pointers and far pointers, sometimes also known as short and long pointers respectively. Near pointers could only point to a 64KB segment of memory determined by one of the x86 segment registers. Far pointers could point to anything. Nowadays in Win32 with virtual memory, there is no need for near pointers -- all pointers are long.
So, an LPSTR is a typedef for a char *, or pointer to a string. An LPCSTR is the const version, i.e. it is a typedef for a const char *. In C, arrays decay into pointers to their first elements, so a char[] decays into a char*. Finally, any type of "pointer to T" (for any type T) can be implicitly converted into a "pointer to const T". Thus, combining these three facts, we see that we can implicitly convert a char[] into an LPCSTR.
In response to your edit, I'm going to guess that you're compiling a Unicode application. If you look carefully at the documentation for CreateFile(), you'll notice that the filename parameter is actually an LPCTSTR, not an LPCSTR (note the T).
For pretty much every Win32 function that takes an argument of some string type (perhaps indirectly, i.e. as a member of a structure passed as a parameter), there are actually two versions of that function: one which takes 8-bit ANSI strings, and one which takes 16-bit wide-character strings. To get the actual function names, you append an A or a W to the function name. So, the ANSI version of CreateFile() is named CreateFileA(), and the wide-character version is named CreateFileW(). Depending on whether or not you're compiling with Unicode enabled (i.e. whether the preprocessor symbol _UNICODE is defined), the symbol CreateFile is #defined to either CreateFileA or CreateFileW as appropriate, and likewise for every other function that has an ANSI and a wide-character version.
Along the same lines, the type TCHAR is typedefed to either char or wchar_t, depending on whether Unicode is enabled, and LPCTSTR is typedefed to a pointer to a const TCHAR.
Thus, to make your code correct, you should replace the strings you're using with TCHAR strings, and use the type-generic version of sprintf_s, _stprintf_s:
TCHAR portName[32];
_stprintf_s(portName, sizeof(portName)/sizeof(TCHAR), _T("\\\\.\\COM%d"), portNum);
CreateFile(portName, ...);
Alternatively, you can explicitly use the ANSI or wide-character versions of everything:
// Use ANSI
char portName[32];
sprintf_s(portName, sizeof(portName), "\\\\.\\COM%d", portNum);
CreateFileA(portName, ...);
// Use wide-characters
wchar_t portName[32];
swprintf_s(portName, sizeof(portName)/sizeof(wchar_t), L"\\\\.\\COM%d", portNum);
CreateFileW(portName, ...);
In what format is your char array?
Is it a const char[] or a non-const?
LPCSTR is just the (somewhat) confusing Microsoft name for "Long Pointer to Constant String".
LPCSTR bar = "hello";
const char *foo = bar;
const char *evil = "hello";
LPCSTR sauron = evil;
If you need to get a non-const version, you either cast away the constness, or you copy to a new array. I would probably prefer the latter. Variables are often const for a reason, and changing them is almost always bad practice.
try like this.........
TCHAR *pcCommPort = TEXT("COM1");
HANDLE h = CreateFile(pcCommPort,other arguments);
char* filename;
LPCTSTR ime = CA2W(filename);
This is String Conversion Macro and works on my VS12
You have string functions for TCHAR. You can use, for example, stprintf_s accepting TCHAR. This way, you make the code "independent" of unicode or multi-byte character set.
Your code (variant 1) becomes:
TCHAR portName[12] = { 0 };
stprintf_s( portName, sizeof( portName ) / sizeof(TCHAR), _T("\\\\.\\COM%i"), portNum );
CreateFile(portName...
"Does anyone know how to convert a char array to a LPCSTR in c?"
You don't have to do anything at all. It automatically converts to that type (except in initializers and sizeof).
"CreateFile(portName..."
Perhaps you should tell us the error message that VC++ gives you at compile time?
Perhaps you should also tell us what error message VC++ gave you when Adam Rosenfield's whcar_t version didn't work for you?
I'm not sure if you figured something out in the end but I had the same problem and following worked well for me:
int comPortNum = 5;
char comPortName[32];
sprintf((LPTSTR)comPortName, TEXT("\\\\.\\COM%d"), comPortNum);
HANDLE h = CreateFile(comPortName,other arguments);
It is an old classical question. I use it in UNICODE.
char *pChar = "My Caption of My application";
WCHAR wsz[512];
swprintf(wsz, L"%S", pChar);
SetWindowText(hWnd, // ウィンドウまたはコントロールのハンドル
wsz // タイトルまたはテキスト
);

Resources