Where is ConnectEx defined? - visual-c++

I want to use ConnectEx function on Windows7, with MSVC2010.
I am getting error C3861: 'ConnectEx': identifier not found
MSDN suggests the function should be declared in mswsock.h, however, when checking it, it's not defined there.
Any tips?

If you read further into the MSDN article for ConnectEx() you mentioned, it says:
Note The function pointer for the ConnectEx function must be obtained
at run time by making a call to the WSAIoctl function with the
SIO_GET_EXTENSION_FUNCTION_POINTER opcode specified. The input buffer
passed to the WSAIoctl function must contain WSAID_CONNECTEX, a
globally unique identifier (GUID) whose value identifies the ConnectEx
extension function. On success, the output returned by the WSAIoctl
function contains a pointer to the ConnectEx function. The
WSAID_CONNECTEX GUID is defined in the Mswsock.h header file.
Unlike other Windows API functions, ConnectEx() must be loaded at runtime, as the header file doesn't actually contain a function declaration for ConnectEx() (it does have a typedef for the function called LPFN_CONNECTEX) and the documentation doesn't specifically mention a specific library that you must link to in order for this to work (which is usually the case for other Windows API functions).
Here's an example of how one could get this to work (error-checking omitted for exposition):
#include <Winsock2.h> // Must be included before Mswsock.h
#include <Mswsock.h>
// Required if you haven't specified this library for the linker yet
#pragma comment(lib, "Ws2_32.lib")
/* ... */
SOCKET s = /* ... */;
DWORD numBytes = 0;
GUID guid = WSAID_CONNECTEX;
LPFN_CONNECTEX ConnectExPtr = NULL;
int success = ::WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
(void*)&guid, sizeof(guid), (void*)&ConnectExPtr, sizeof(ConnectExPtr),
&numBytes, NULL, NULL);
// Check WSAGetLastError()!
/* ... */
// Assuming the pointer isn't NULL, you can call it with the correct parameters.
ConnectExPtr(s, name, namelen, lpSendBuffer,
dwSendDataLength, lpdwBytesSent, lpOverlapped);

Related

using a globals struct in several .cpp files, and initializing it in the constructor

I know similar questions have been asked, but none address this issue. I want to create a globals struct and initialize it with default values. I implemented it as below, but the project won't build.
I've tried everything I can think of, most notably moving the "extern" declaration of *gxg in and out of the header guard and changing the struct to a class, but get the same results: the project won't build because of duplicate symbols for the globals constructor. It builds if I don't use it in more than one .cpp file, or if I don't include a constructor or destructor in the struct's implementation file.
// globals.hpp
#ifndef globals_hpp
#define globals_hpp
struct gxGlobals{
double radius;
bool easement;
gxGlobals(); // constructor
} ;
extern "C" gxGlobals *gxg;
#endif /* globals_hpp */
—————————————
// globals.cpp
#include "globals.hpp"
gxGlobals::gxGlobals():
radius(24),
easement(false)
{};
———————————
// main_file.cpp
#include "globals.hpp"
gxGlobals *gxg = new gxGlobals();
———————————
// other_file.cpp
#include "globals.hpp"
// ERROR: Duplicate symbol gxGlobals::gxGlobals()
I can include globals.h in one file, but not in two or more. It also works if I remove the self-initialization in the .cpp file.
There are too many members in the actual struct to make an initializer list practical, so my last option is a function that runs on startup that plugs all of the default values in. Am I mistaken that this should work?

Why doesn't MSVC initialize this const struct?

I have some code written in C, and there is one section that refuses to cooperate when using Visual Studio 2015 Community (clang has no problems). I have a simple struct:
/** Options for enumerating over all documents. */
typedef struct {
unsigned skip; /**< The number of initial results to skip. */
C4EnumeratorFlags flags; /**< Option flags */
} C4EnumeratorOptions;
enum {
kC4Descending = 0x01, /**< If true, iteration goes by descending document IDs. */
kC4InclusiveStart = 0x02, /**< If false, iteration starts just _after_ startDocID. */
kC4InclusiveEnd = 0x04, /**< If false, iteration stops just _before_ endDocID. */
kC4IncludeDeleted = 0x08, /**< If true, include deleted documents. */
kC4IncludeNonConflicted = 0x10, /**< If false, include _only_ documents in conflict. */
kC4IncludeBodies = 0x20 /**< If false, document bodies will not be preloaded, just
metadata (docID, revID, sequence, flags.) This is faster if you
don't need to access the revision tree or revision bodies. You
can still access all the data of the document, but it will
trigger loading the document body from the database. */
};
typedef uint16_t C4EnumeratorFlags;
And I also have a constant "default" value for it:
// In header
extern const C4EnumeratorOptions kC4DefaultEnumeratorOptions;
// In implementation
const C4EnumeratorOptions kC4DefaultEnumeratorOptions = {
0, // skip
kC4InclusiveStart | kC4InclusiveEnd | kC4IncludeNonConflicted | kC4IncludeBodies
};
However, when debugging I noticed that the initialization is not doing anything when I try to use the default value:
// options winds up with a "skip" value of something like 117939945
// and a flags value of 59648
C4EnumeratorOptions options = kC4DefaultEnumeratorOptions;
The section defining is in a DLL, and the second using is in an exe. Again, this only happens on Windows. Furthermore, the value in "options" is garbage but for some reason it's not even the same garbage that is stored in kC4DefaultEnumeratorOptions. I know MSVC is notorious for snubbing C, but this kind of initialization is so old that even MSVC should get it right, shouldn't it? So it must be something I am doing but I can't figure out what.
EDIT The symbol is being exported via a export definitions file. I checked with dumpbin, and found the symbol in the exported symbols list
41 46 00A6EA8 kC4DefaultEnumeratorOptions = kC4DefaultEnumeratorOptions
Also as one more bit of info, the calling code is C++ and the DLL code is C, which I suspect may be playing a part in this madness.
The comments from #M.M helped put me in the right direction. He asked if the symbol was exported. Technically, yes, it was exported since it was in the export list but apparently I also need to export the definition. So instead of including the global symbol in the .def file, I need to manually mark it with __declspec(dllexport) or __declspec(dllimport) in two places so in the end it looks like this:
#ifdef _MSC_VER
#ifdef CBFOREST_EXPORTS
#define CBFOREST_API __declspec(dllexport)
#else
#define CBFOREST_API __declspec(dllimport)
#endif
#endif
// ...
// Header
CBFOREST_API extern const C4EnumeratorOptions kC4DefaultEnumeratorOptions;
// Implementation
CBFOREST_API const C4EnumeratorOptions kC4DefaultEnumeratorOptions = {
0, // skip
kC4InclusiveStart | kC4InclusiveEnd | kC4IncludeNonConflicted | kC4IncludeBodies
};

What is the correct monotouch binding for this?

It seems most of the examples regarding binding an Objective-C library to c# show methods and properties, but what do you do with instance variables that are declared?
Here's an example of the .h file I'm trying to create a binding for:
#interface NdefRecord : NSObject
{
#public
uint8_t Flags;
NDEF_TNF_Type Tnf;
uint8_t TypeLength;
uint8_t *Type;
uint8_t IdLength;
uint8_t *Id;
uint32_t PayloadLength;
uint8_t *PayloadData;
}
/**
Initialize this record.
- Optional: Since member fields are public, you can also set them directly.
*/
- (id) init:(NDEF_TNF_Type)tnf type:(NSData*)type Id:(NSData*)IdBytes payload:(NSData*)payload;
/**
Parse an NDEF Record from raw bytes.
*/
- (BOOL) parse:(UInt8*)data;
/**
Returns this entire NDEF Record as a byte array.
*/
- (uint32_t) toByteArray:(UInt8*)buffer;
...
#end
In my binding project, things like the parse: method are easy enough to bind, but things like TypeLength and *Type were missed by Objective Sharpie, and nothing I seem to hand create works properly.
In an iOS XCode project, those variables are accessed with syntax like so:
record->TypeLength instead of [record TypeLength] which leads me to believe a simple binding like:
[Export ("TypeLength")]
Byte TypeLength { get; set; }
isn't going to work.
I'm completely stuck on a solution here, so any guidance is much appreciated!
The binding tool does not support accessing internal fields of a class, which is what you are trying to do here.
The only thing you can bind with an [Export] are actual properties and methods.
You need to alter that library to expose properties to those internals.

Why the bad_alloc(const char*) was made private in Visual C++ 2012?

I am just trying to compile a bit bigger project using the Visual Studio 2012 Release Candidate, C++. The project was/is compiled using the VS2010 now. (I am just greedy to get the C++11 things, so I tried. :)
Apart of things that I can explain by myself, the project uses the code like this:
ostringstream ostr;
ostr << "The " __FUNCTION__ "() failed to malloc(" << i << ").";
throw bad_alloc(ostr.str().c_str());
The compiler now complains
error C2248: 'std::bad_alloc::bad_alloc' : cannot access private member declared
in class 'std::bad_alloc'
... which is true. That version of constructor is now private.
What was the reason to make that version of constructor private? Is it recommended by C++11 standard not to use that constructor with the argument?
(I can imagine that if allocation failed, it may cause more problems to try to construct anything new. However, it is only my guess.)
Thanks,
Petr
The C++11 Standard defines bad_alloc as such (18.6.2.1):
class bad_alloc : public exception {
public:
bad_alloc() noexcept;
bad_alloc(const bad_alloc&) noexcept;
bad_alloc& operator=(const bad_alloc&) noexcept;
virtual const char* what() const noexcept;
};
With no constructor that takes a string. A vendor providing such a constructor would make the code using it not portable, as other vendors are not obliged to provide it.
The C++03 standard defines a similar set of constructors, so VS didn't follow this part of the standard even before C++11. MS does try to make VS as standard compliant as possible, so they've probably just used the occasion (new VS, new standard) to fix an incompatibility.
Edit: Now that I've seen VS2012's code, it is also clear why the mentioned constructor is left private, instead of being completely removed: there seems to be only one use of that constructor, in the bad_array_new_length class. So bad_array_new_length is declared a friend in bad_alloc, and can therefore use that private constructor. This dependency could have been avoided if bad_array_new_length just stored the message in the pointer used by what(), but it's not a lot of code anyway.
If you are accustomed to passing a message when you throw a std::bad_alloc, a suitable technique is to define an internal class that derives from std::bad_alloc, and override ‘what’ to supply the appropriate message.
You can make the class public and call the assignment constructor directly, or make a helper function, such as throw_bad_alloc, which takes the parameters (and additional scalar information) and stores them in the internal class.
The message is not formatted until ‘what’ is called. In this way, stack unwinding may have freed some memory so the message can be formatted with the actual reason (memory exhaustion, bad request size, heap corruption, etc.) at the catch site. If formatting fails, simply assign and return a static message.
Trimmed example:
(Tip: The copy constructor can just assign _Message to nullptr, rather than copy the message since the message is formatted on demand. The move constructor, of course can just confiscate it :-).
class internal_bad_alloc: public std::bad_alloc
{
public:
// Default, copy and move constructors....
// Assignment constructor...
explicit internal_bad_alloc(int errno, size_t size, etc...) noexcept:
std::bad_alloc()
{
// Assign data members...
}
virtual ~internal_bad_alloc(void) noexcept
{
// Free _Message data member (if allocated).
}
// Override to format and return the reason:
virtual const char* what(void) const noexcept
{
if (_Message == nullptr)
{
// Format and assign _Message. Assign the default if the
// format fails...
}
return _Message;
}
private:
// Additional scalar data (error code, size, etc.) pass into the
// constructor and used when the message is formatted by 'what'...
mutable char* _Message;
static char _Default[];
}
};
//
// Throw helper(s)...
//
extern void throw_bad_alloc(int errno, size_t size, etc...)
{
throw internal_bad_alloc(errno, size, etc...);
}

Is it possible to pass an std::string via Microsoft RPC?

I tried passing an std::string via RPC, but I got the following error:
MIDL2025: syntax error: expecting a
type specification or a storage
specifer or a type qualifier near
"string"
Extract from code:
interface TestInterface
{
unsigned int HelloUser([in] const string user);
}
Is this possible?
You must use a BSTR. Also, no const. By specifying the argument as [in], it is already understood that the callee will not modify the string, and even if it did modify, it won't be marshaled back to the caller.
The _bstr_t class will help with conversion. Note that BSTR is always based on WCHAR, which is 16-bit. Thus, use std::wstring.

Resources